replywizard-whatsapp-mcp 0.2.6 → 0.2.7

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
@@ -32,7 +32,7 @@ lifted into its own repository without touching the extension.
32
32
  | `get_contact` | read | Look up one contact by id. |
33
33
  | `list_contacts` | read | Your saved (address-book) contacts. |
34
34
  | `summarize_chat` | value | Bulleted summary of a chat's recent messages (uses your configured AI provider). |
35
- | `suggest_reply` | value | Drafts a reply as you — returns text only, **never sends**. |
35
+ | `suggest_reply` | value | Drafts a reply as you, returns text only, **never sends**. |
36
36
  | `transcribe_voice_note` | value | Transcribes a voice note via your configured **cloud** speech-to-text provider. |
37
37
 
38
38
  Value tools reuse the extension's existing AI/STT configuration; **your API keys never leave the
@@ -41,13 +41,13 @@ extension** (the hub only sees tool arguments and results).
41
41
  ## Setup
42
42
 
43
43
  > **Multi-agent by default.** The `npx -y replywizard-whatsapp-mcp` config below runs the **connector**
44
- > (the package's default bin), which auto-starts a shared local **daemon** — so several assistants
44
+ > (the package's default bin), which auto-starts a shared local **daemon**, so several assistants
45
45
  > (Claude Code + Cursor + Claude Desktop, …) can share one WhatsApp session at once, with no extra setup.
46
46
  > See [Multiple AI assistants at once](#multiple-ai-assistants-at-once-daemon) for the architecture. Use
47
47
  > the single-arg form above (not the older `-p <pkg> <bin>` form, which some clients fail to launch).
48
48
 
49
49
  Published to npm as [`replywizard-whatsapp-mcp`](https://www.npmjs.com/package/replywizard-whatsapp-mcp).
50
- You don't install anything by hand — your AI client runs it via `npx` (requires Node.js 18+).
50
+ You don't install anything by hand, your AI client runs it via `npx` (requires Node.js 18+).
51
51
 
52
52
  ### Claude Desktop
53
53
 
@@ -71,17 +71,32 @@ Add to `claude_desktop_config.json`:
71
71
  claude mcp add replywizard -- npx -y replywizard-whatsapp-mcp
72
72
  ```
73
73
 
74
+ ### Cursor and VS Code: one click
75
+
76
+ The extension's **WhatsApp MCP** tab has **Add to Cursor** and **Add to VS Code** buttons that
77
+ hand the editor exactly the config above, plus a copy button for the Claude Code command. The raw
78
+ JSON stays on screen next to them: an install deeplink is opaque by nature, so reading it first is
79
+ always an option.
80
+
74
81
  `RW_MCP_PORT` is optional (defaults to `7869`); set it on both sides if you change it.
75
82
 
83
+ > **Pairing-code toast.** The code is also shown as a desktop notification (`osascript` on
84
+ > macOS, a PowerShell balloon on Windows, `notify-send` on Linux), because the connector is
85
+ > usually launched in the background where stderr is invisible. It is best-effort and never
86
+ > fails the daemon; `~/.replywizard-mcp/pairing-code.txt` (0600) is the backstop. All three
87
+ > branches run in CI on their own platform, `npm test` in this package covers them, and the
88
+ > real-notifier test is skipped locally unless `CI=1` or `RW_TEST_NOTIFY=1` so running the
89
+ > suite does not interrupt you with a toast.
90
+
76
91
  > **Running from source instead?** Clone the repo, `cd mcp-host && npm install`, and point your
77
- > client at `node /absolute/path/to/mcp-host/src/connector.js` (multi-agent) — or
92
+ > client at `node /absolute/path/to/mcp-host/src/connector.js` (multi-agent), or
78
93
  > `node .../src/index.js` for the legacy single-client, no-daemon hub.
79
94
 
80
95
  ## Multiple AI assistants at once (daemon)
81
96
 
82
97
  This happens automatically with the `npx` config above: `replywizard-whatsapp-mcp` runs the connector,
83
- which starts one shared daemon. (The legacy `index.js` hub — run directly via `node .../src/index.js` —
84
- binds the WebSocket port itself, so **only one AI client can use it at a time**; a second launch hits
98
+ which starts one shared daemon. (The legacy `index.js` hub, run directly via `node .../src/index.js`, binds
99
+ the WebSocket port itself, so **only one AI client can use it at a time**; a second launch hits
85
100
  `EADDRINUSE`.) The daemon architecture:
86
101
 
87
102
  ```
@@ -90,12 +105,12 @@ client B (stdio)→ rw-mcp-connector ─┤→ rw-mcp-daemon ⇄ Reply Wizard
90
105
  client C (stdio)→ rw-mcp-connector ─┘ (one daemon; owns ws://127.0.0.1:7869, serves http://127.0.0.1:7870/mcp)
91
106
  ```
92
107
 
93
- - **`rw-mcp-daemon`** — long-lived; owns the extension WebSocket and serves MCP over Streamable HTTP
108
+ - **`rw-mcp-daemon`**: long-lived; owns the extension WebSocket and serves MCP over Streamable HTTP
94
109
  to any number of clients (each gets its own session). Single-instance: a second daemon exits cleanly.
95
- - **`rw-mcp-connector`** — a stdio shim for clients that only launch a command; it auto-starts the
110
+ - **`rw-mcp-connector`**: a stdio shim for clients that only launch a command; it auto-starts the
96
111
  daemon if needed and transparently proxies. **Reads the auth token for you** (no token in your config).
97
112
 
98
- **Clients that speak HTTP (e.g. Claude Code)** connect to the daemon directly — no connector needed:
113
+ **Clients that speak HTTP (e.g. Claude Code)** connect to the daemon directly, no connector needed:
99
114
 
100
115
  ```bash
101
116
  TOKEN=$(node -e "console.log(require('os').homedir())")/.replywizard-mcp/daemon-token.json # see the token
@@ -128,24 +143,43 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
128
143
  The daemon generates a bearer token on first start at `~/.replywizard-mcp/daemon-token.json` (mode
129
144
  `600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz` is open.
130
145
  The connector reads it automatically. **To revoke**, delete that file (the daemon mints a new one on
131
- next start) — existing clients must pick up the new token.
146
+ next start): existing clients must pick up the new token.
132
147
 
133
148
  ## First-run pairing
134
149
 
135
150
  1. Open **WhatsApp Web** in the browser with Reply Wizard installed.
136
- 2. Click the Reply Wizard toolbar icon → **AI client access** → **Enable AI access**.
151
+ 2. Open Reply Wizard **Settings** → **WhatsApp MCP** and turn on **Enable AI access**. The
152
+ toolbar popup reports the same state under **AI client access** and has a **Manage in
153
+ Settings** button that jumps straight there, but every control lives on the tab.
137
154
  3. Start your AI client (it launches this hub). The hub prints a **6-digit pairing code** to its
138
155
  stderr / the client's MCP log.
139
- 4. Enter that code in the extension popup. Once paired, the extension stores a session token and
140
- reconnects automatically on subsequent runs (no code needed again).
156
+ 4. Enter that code in **Settings → WhatsApp MCP**. Once paired, the extension stores a session
157
+ token and reconnects automatically on subsequent runs (no code needed again).
158
+
159
+ Use **Revoke pairing** on the same tab to drop the token and disable the bridge.
160
+
161
+ **A code survives a reconnect.** The extension's MV3 service worker reconnects on its own
162
+ schedule, and until 2026-09-03 each reconnect threw the pairing code away and minted a new one,
163
+ so the digits you were reading off the toast went stale while you typed them and another toast
164
+ appeared. A code that is still within its five minutes is now reused instead: one code, one
165
+ notification, and it stays valid for as long as it was ever going to.
166
+
167
+ Two things do **not** change on reuse, and each is tested:
168
+
169
+ - **The deadline is not extended.** The five minutes run from when the code was first issued,
170
+ so a client that reconnects every four minutes cannot keep one code alive indefinitely.
171
+ - **The wrong-attempt counter is not reset.** This is the load-bearing half. Without it,
172
+ closing and reopening the socket would hand an attacker another five guesses against the
173
+ same code, over and over; the old behaviour was safe only because the code changed each
174
+ time, so preserving one property without the other would have been a regression.
141
175
 
142
- Use **Revoke access** in the popup to drop the token and disable the bridge.
176
+ A code is still destroyed immediately on a successful pairing, on lockout, and on expiry.
143
177
 
144
178
  ## Security
145
179
 
146
180
  - Binds to `127.0.0.1` only.
147
181
  - No tool runs until the pairing code is confirmed in the extension.
148
- - **Read + value tools only** — v1 has no send/modify capability.
182
+ - **Read + value tools only**: v1 has no send/modify capability.
149
183
  - The session token is stored at `~/.replywizard-mcp/session.json` (mode 600).
150
184
 
151
185
  ## Troubleshooting
@@ -158,5 +192,5 @@ Use **Revoke access** in the popup to drop the token and disable the bridge.
158
192
  | Transcription error about a cloud provider | `transcribe_voice_note` needs a **cloud** STT key in Options → Speech-to-Text (on-device STT is not used over MCP). |
159
193
  | Port in use | The default is `7869`. Changing it is advanced (set `RW_MCP_PORT` on the hub **and** the `rw_mcp_port` value in the extension's storage to match). |
160
194
 
161
- See [`../docs/MCP_EXECUTION_PLAN.md`](../docs/MCP_EXECUTION_PLAN.md) and
162
- [`../docs/MCP_INTEGRATION_IMPLEMENTATION_PLAN.md`](../docs/MCP_INTEGRATION_IMPLEMENTATION_PLAN.md).
195
+ See [`../ARCHITECTURE.md`](../ARCHITECTURE.md) (MCP Integration) for the design, and
196
+ [`../ROADMAP.md`](../ROADMAP.md) §3.4 for the open MCP items.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "Local MCP server that exposes WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/connector.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // connector.js — stdio↔daemon proxy for MCP clients that only speak stdio (WS-A2).
2
+ // connector.js: stdio↔daemon proxy for MCP clients that only speak stdio (WS-A2).
3
3
  //
4
4
  // Clients that support HTTP transport connect to the daemon directly
5
5
  // (claude mcp add rw --transport http http://127.0.0.1:7870/mcp). Clients that only
@@ -8,7 +8,7 @@
8
8
  // 2. transparently pumps JSON-RPC frames between its stdio (facing the client) and
9
9
  // a Streamable-HTTP client transport (facing the daemon).
10
10
  //
11
- // It owns no MCP logic — it relays at the transport layer, so every tool/version the
11
+ // It owns no MCP logic: it relays at the transport layer, so every tool/version the
12
12
  // daemon supports works without changes here. ALL logging goes to stderr (stdout is
13
13
  // reserved for the MCP stdio protocol). Mirrors Kaption's `@kaptionai/mcp-extension` shim.
14
14
 
@@ -26,7 +26,7 @@ const delay = (ms) => new Promise((r) => setTimeout(r, ms));
26
26
 
27
27
  /**
28
28
  * Wire two MCP transports so every message on one is forwarded to the other, in both
29
- * directions, and a close/error on either tears down the pair. Pure plumbing — no
29
+ * directions, and a close/error on either tears down the pair. Pure plumbing: no
30
30
  * protocol knowledge. Returns nothing; assign the transports' lifecycle to the caller.
31
31
  */
32
32
  export function pumpTransports(clientFacing, daemonFacing) {
package/src/daemon.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- // daemon.js — long-lived multi-client MCP daemon (Option A, WS-A1).
2
+ // daemon.js: long-lived multi-client MCP daemon (Option A, WS-A1).
3
3
  //
4
4
  // The original index.js binds ONE stdio client and ONE extension WebSocket per
5
5
  // process, so two AI clients fight over the port (the v3.1.5 EADDRINUSE case). This
6
6
  // daemon instead:
7
7
  // • owns a single ExtensionBridge (the extension dials into ws://127.0.0.1:7869), and
8
8
  // • serves MCP over Streamable HTTP at http://127.0.0.1:7870/mcp to ANY number of
9
- // clients — each client gets its own MCP session (a fresh Server + transport),
9
+ // clients: each client gets its own MCP session (a fresh Server + transport),
10
10
  // and they all share the one extension bridge.
11
11
  //
12
12
  // Clients connect either directly (claude mcp add rw --transport http
@@ -94,7 +94,7 @@ export function createDaemon({
94
94
  // Relay the distinct names of currently-connected MCP clients to the extension,
95
95
  // so the options page can show which AI assistants are attached. Names come from
96
96
  // each client's `initialize` clientInfo (the stdio connector pumps frames raw, so
97
- // the real client's name — "Antigravity", "Cursor", … — reaches us verbatim).
97
+ // the real client's name ("Antigravity", "Cursor", …) reaches us verbatim).
98
98
  function publishClients() {
99
99
  if (!bridge || typeof bridge.setConnectedClients !== 'function') return;
100
100
  const seen = new Set();
@@ -236,14 +236,14 @@ export async function main() {
236
236
  let shutdownFn = () => process.exit(0); // replaced below once daemon exists
237
237
  const daemon = createDaemon({
238
238
  bridge, httpPort, idleMs, staleSessionMs, sweepIntervalMs,
239
- onIdle: () => { log(`Idle for ${Math.round(idleMs / 1000)}s with no sessions — shutting down.`); shutdownFn(); },
239
+ onIdle: () => { log(`Idle for ${Math.round(idleMs / 1000)}s with no sessions, shutting down.`); shutdownFn(); },
240
240
  });
241
241
 
242
242
  // Single-instance lock: the HTTP port is the daemon's identity. If it is taken,
243
- // another daemon already owns it — exit cleanly rather than crash-loop.
243
+ // another daemon already owns it: exit cleanly rather than crash-loop.
244
244
  daemon.httpServer.on('error', (err) => {
245
245
  if (err && err.code === 'EADDRINUSE') {
246
- log(`HTTP port ${httpPort} is in use — another Reply Wizard daemon is already running. Exiting.`);
246
+ log(`HTTP port ${httpPort} is in use, another Reply Wizard daemon is already running. Exiting.`);
247
247
  try { bridge.close(); } catch { /* noop */ }
248
248
  process.exit(0);
249
249
  }
@@ -263,7 +263,7 @@ export async function main() {
263
263
 
264
264
  // Run only when invoked directly as the bin entry (not when imported by tests).
265
265
  // argv[1] may be a bin SYMLINK (npx / global / `rw-mcp-daemon`) while import.meta.url is the
266
- // real file — resolve symlinks on both sides before comparing, else main() silently no-ops.
266
+ // real file: resolve symlinks on both sides before comparing, else main() silently no-ops.
267
267
  export function invokedAsEntry() {
268
268
  if (!process.argv[1]) return false;
269
269
  try {
package/src/daemonAuth.js CHANGED
@@ -1,4 +1,4 @@
1
- // daemonAuth.js — local client-auth token for the MCP daemon (WS-A4).
1
+ // daemonAuth.js: local client-auth token for the MCP daemon (WS-A4).
2
2
  //
3
3
  // The daemon listens on loopback, but any local process could otherwise reach it and
4
4
  // read WhatsApp through a paired extension. This adds a bearer token that clients must
@@ -25,6 +25,14 @@ function tokenFile(dir) {
25
25
  return join(stateDir(dir), 'daemon-token.json');
26
26
  }
27
27
 
28
+ // 0o600 is honoured on Linux and macOS: owner read/write, nobody else. It is NOT
29
+ // honoured on Windows, where Node's `mode` option controls only the read-only flag and
30
+ // stat reports 0666 regardless. There the file's protection is the ACL on the user
31
+ // profile directory, which keeps other *users* out but not another process running as
32
+ // this user, nor an administrator. That is a weaker guarantee, and it is stated here
33
+ // rather than implied by the constant. The token is local-only and rotatable
34
+ // (`rotateToken`), which is what keeps the difference tolerable rather than a hole.
35
+ // Surfaced by the cross-platform CI matrix, 2026-08-20.
28
36
  function writeToken(token, dir) {
29
37
  try {
30
38
  mkdirSync(stateDir(dir), { recursive: true });
package/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // index.js — replywizard-mcp entry point.
2
+ // index.js: replywizard-mcp entry point.
3
3
  //
4
4
  // Starts the local WebSocket server (which the extension dials into) and the MCP
5
5
  // stdio server (which the AI client connects to), and bridges the two.
package/src/mcpServer.js CHANGED
@@ -1,4 +1,4 @@
1
- // mcpServer.js — the MCP server presented to the AI client over stdio.
1
+ // mcpServer.js: the MCP server presented to the AI client over stdio.
2
2
  //
3
3
  // Translates MCP tools/list and tools/call into extension actions via the
4
4
  // ExtensionBridge WebSocket. Returns tool results as JSON text content.
package/src/protocol.js CHANGED
@@ -1,4 +1,4 @@
1
- // protocol.js — wire contract shared with the Reply Wizard extension.
1
+ // protocol.js: wire contract shared with the Reply Wizard extension.
2
2
  //
3
3
  // This is a self-contained copy so the hub can be spun off into its own repo.
4
4
  // While co-located in the extension repo, `tests/mcpProtocol.test.js` asserts the
package/src/tools.js CHANGED
@@ -1,4 +1,4 @@
1
- // tools.js — MCP tool definitions exposed to the AI client.
1
+ // tools.js: MCP tool definitions exposed to the AI client.
2
2
  //
3
3
  // Each tool maps 1:1 to an extension action (see protocol.js ACTIONS). The hub's
4
4
  // CallTool handler forwards `arguments` to the extension over the WebSocket and
@@ -40,7 +40,12 @@ export const TOOLS = [
40
40
  inputSchema: {
41
41
  type: 'object',
42
42
  properties: {
43
- chatId: { type: 'string', description: 'Chat id from list_chats (e.g. "12345@g.us").' },
43
+ chatId: {
44
+ type: 'string',
45
+ description: 'Chat id from list_chats, e.g. "84726351928374@lid" (one-to-one) or ' +
46
+ '"12345-1600000000@g.us" (group). A plain phone number in digits also resolves ' +
47
+ 'to a one-to-one chat, e.g. "919110412164".',
48
+ },
44
49
  limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Max messages (default 30).' },
45
50
  },
46
51
  required: ['chatId'],
@@ -53,7 +58,13 @@ export const TOOLS = [
53
58
  inputSchema: {
54
59
  type: 'object',
55
60
  properties: {
56
- contactId: { type: 'string', description: 'Contact id (e.g. "12345@c.us").' },
61
+ contactId: {
62
+ type: 'string',
63
+ description:
64
+ 'Contact id from list_contacts, e.g. "84726351928374@lid" or the legacy ' +
65
+ '"919110412164@c.us". A plain phone number in digits also resolves, e.g. ' +
66
+ '"919110412164".',
67
+ },
57
68
  },
58
69
  required: ['contactId'],
59
70
  additionalProperties: false,
@@ -80,7 +91,7 @@ export const TOOLS = [
80
91
  inputSchema: {
81
92
  type: 'object',
82
93
  properties: {
83
- chatId: { type: 'string', description: 'Chat id from list_chats.' },
94
+ chatId: { type: 'string', description: 'Chat id from list_chats, or a phone number in digits.' },
84
95
  limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Messages to summarize (default 40).' },
85
96
  },
86
97
  required: ['chatId'],
@@ -91,11 +102,11 @@ export const TOOLS = [
91
102
  name: ACTIONS.SUGGEST_REPLY,
92
103
  description:
93
104
  'Draft a suggested reply (as the user) to a chat, based on its recent messages. ' +
94
- 'Returns the suggestion text only — it does NOT send anything.',
105
+ 'Returns the suggestion text only: it does NOT send anything.',
95
106
  inputSchema: {
96
107
  type: 'object',
97
108
  properties: {
98
- chatId: { type: 'string', description: 'Chat id from list_chats.' },
109
+ chatId: { type: 'string', description: 'Chat id from list_chats, or a phone number in digits.' },
99
110
  limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Context messages (default 20).' },
100
111
  guidance: { type: 'string', description: 'Optional steer, e.g. "politely decline" or "ask for a call".' },
101
112
  },
package/src/wsServer.js CHANGED
@@ -1,4 +1,4 @@
1
- // wsServer.js — local WebSocket server the extension dials into.
1
+ // wsServer.js: local WebSocket server the extension dials into.
2
2
  //
3
3
  // The Reply Wizard extension (background SW) is the WebSocket *client*; this hub is
4
4
  // the server, bound to 127.0.0.1 only.
@@ -58,43 +58,101 @@ function sixDigitCode() {
58
58
  return String(parseInt(randomBytes(4).toString('hex'), 16) % 1_000_000).padStart(6, '0');
59
59
  }
60
60
 
61
+ // Number of wrong pairing codes tolerated before the active code is invalidated
62
+ // (a fresh handshake is then required to mint a new one). Bounds online guessing
63
+ // of the 6-digit (1e6) space to a handful of tries per code.
64
+ const MAX_PAIRING_ATTEMPTS = 5;
65
+ // A pairing code auto-expires this long after it is issued, so a code left on
66
+ // screen can't be brute-forced indefinitely.
67
+ const PAIRING_CODE_TTL_MS = 5 * 60_000;
68
+
69
+ // Decide whether a WebSocket handshake's Origin is allowed. WebSocket is NOT
70
+ // subject to same-origin policy, so any http(s) page a user has open could
71
+ // otherwise dial ws://127.0.0.1:<port> and race for the single connection slot
72
+ // to brute-force pairing. The legitimate client is the extension's MV3 service
73
+ // worker (Origin `chrome-extension://<id>`); a Node/CLI client sends no Origin.
74
+ // We allow those two and reject page origins (http/https/file/etc). Exported for
75
+ // tests. Default-allow only for a genuinely absent Origin, never for a page.
76
+ export function isAllowedOrigin(origin) {
77
+ if (!origin) return true; // Node/CLI client: no Origin header
78
+ if (origin.startsWith('chrome-extension://')) return true;
79
+ if (origin.startsWith('moz-extension://')) return true; // future Firefox/Edge port
80
+ return false; // http(s):// page or anything else
81
+ }
82
+
61
83
  // Surface the pairing code as an OS desktop notification so a non-technical user
62
84
  // sees it WITHOUT a terminal (the connector launches us in the background, where
63
85
  // stderr is invisible). This is a valid out-of-band channel: only someone at the
64
86
  // physical machine sees the toast, so it does not weaken pairing the way echoing
65
87
  // the code over the (untrusted) extension socket would. Best-effort: never throws,
66
- // never blocks (detached + unref + stdio ignore), silent if the tool is missing —
88
+ // never blocks (detached + unref + stdio ignore), silent if the tool is missing;
67
89
  // the 0600 file and stderr remain as backstops. `code` is digits-only (no shell/
68
90
  // AppleScript injection risk). Exported for tests.
69
- export function notifyPairingCode(code) {
70
- const title = 'Reply Wizard pairing code';
71
- const body = `Enter ${code} in Reply Wizard (AI Assistants > MCP) to connect.`;
91
+ export const PAIRING_NOTIFY_TITLE = 'Reply Wizard pairing code';
92
+
93
+ /**
94
+ * The command that shows the toast on one platform. Split out from the spawn so the
95
+ * three branches can be asserted, and actually RUN, on all three platforms in CI: until
96
+ * 2026-08-20 the macOS and Windows branches had never once executed anywhere but a
97
+ * developer's own machine, and a toast that silently does nothing is invisible by
98
+ * construction (this whole function is best-effort by design).
99
+ *
100
+ * @param {string} code the 6-digit pairing code
101
+ * @param {string} [os] platform() by default; passed explicitly by tests
102
+ * @returns {{cmd: string, args: string[]}}
103
+ */
104
+ export function pairingNotifyCommand(code, os = platform()) {
105
+ const title = PAIRING_NOTIFY_TITLE;
106
+ const body = `Enter ${code} in Reply Wizard (Settings > WhatsApp MCP) to connect.`;
107
+ if (os === 'darwin') {
108
+ // AppleScript has no parameter binding, so the text is escaped rather than trusted.
109
+ // `code` is digits-only today; this is what keeps that from being load-bearing.
110
+ const esc = (s) => s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
111
+ return { cmd: 'osascript', args: ['-e', `display notification "${esc(body)}" with title "${esc(title)}"`] };
112
+ }
113
+ if (os === 'win32') {
114
+ // PowerShell balloon via WinForms: no external module required. System.Drawing is
115
+ // loaded explicitly because SystemIcons lives there; relying on WinForms to drag it
116
+ // in works on some hosts and throws on others, which is exactly the failure this
117
+ // branch could never see before it ran in CI.
118
+ const ps =
119
+ 'Add-Type -AssemblyName System.Windows.Forms;' +
120
+ 'Add-Type -AssemblyName System.Drawing;' +
121
+ '$n=New-Object System.Windows.Forms.NotifyIcon;' +
122
+ '$n.Icon=[System.Drawing.SystemIcons]::Information;' +
123
+ `$n.BalloonTipTitle=${JSON.stringify(title)};` +
124
+ `$n.BalloonTipText=${JSON.stringify(body)};` +
125
+ '$n.Visible=$true;$n.ShowBalloonTip(20000);Start-Sleep -Seconds 8;$n.Dispose()';
126
+ return { cmd: 'powershell', args: ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', ps] };
127
+ }
128
+ // Linux / *nix: libnotify.
129
+ return { cmd: 'notify-send', args: ['-u', 'normal', '-t', '30000', title, body] };
130
+ }
131
+
132
+ /**
133
+ * Show the toast. Best-effort: never throws, never blocks, silent if the tool is missing.
134
+ *
135
+ * @param {string} code the six-digit pairing code
136
+ * @param {Function} [spawnFn] injected by tests, so proving "a missing notifier is not an
137
+ * outage" does not require actually spawning a notifier. It used to, and the cost was
138
+ * three real desktop toasts on the developer's screen every time the suite ran, two of
139
+ * them reading "Enter undefined" and "Enter " because those were the arguments under
140
+ * test. A test that has to be watched to be believed is a test nobody watches.
141
+ * @returns {boolean} whether a notification was attempted
142
+ */
143
+ export function notifyPairingCode(code, spawnFn = spawn) {
144
+ // A toast reading "Enter undefined in Reply Wizard" is worse than no toast: it tells
145
+ // somebody to type a word. Nothing in the daemon can produce one today, because the
146
+ // code is minted immediately before this call, and that is exactly the kind of thing
147
+ // that stops being true later.
148
+ if (typeof code !== 'string' || !/^\d{4,10}$/.test(code)) return false;
72
149
  try {
73
- let cmd, args;
74
- const os = platform();
75
- if (os === 'darwin') {
76
- cmd = 'osascript';
77
- args = ['-e', `display notification "${body}" with title "${title}"`];
78
- } else if (os === 'win32') {
79
- // PowerShell balloon via WinForms — no external module required.
80
- const ps =
81
- 'Add-Type -AssemblyName System.Windows.Forms;' +
82
- '$n=New-Object System.Windows.Forms.NotifyIcon;' +
83
- '$n.Icon=[System.Drawing.SystemIcons]::Information;' +
84
- `$n.BalloonTipTitle=${JSON.stringify(title)};` +
85
- `$n.BalloonTipText=${JSON.stringify(body)};` +
86
- '$n.Visible=$true;$n.ShowBalloonTip(20000);Start-Sleep -Seconds 8;$n.Dispose()';
87
- cmd = 'powershell';
88
- args = ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', ps];
89
- } else {
90
- // Linux / *nix: libnotify.
91
- cmd = 'notify-send';
92
- args = ['-u', 'normal', '-t', '30000', title, body];
93
- }
94
- const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
95
- child.on('error', () => {}); // tool absent (e.g. no notify-send) — stay silent
96
- child.unref();
97
- } catch { /* notifications are best-effort */ }
150
+ const { cmd, args } = pairingNotifyCommand(code);
151
+ const child = spawnFn(cmd, args, { stdio: 'ignore', detached: true });
152
+ child?.on?.('error', () => {}); // tool absent (e.g. no notify-send): stay silent
153
+ child?.unref?.();
154
+ return true;
155
+ } catch { /* notifications are best-effort */ return false; }
98
156
  }
99
157
 
100
158
  export class ExtensionBridge {
@@ -106,6 +164,11 @@ export class ExtensionBridge {
106
164
  this.socket = null; // the single connected extension socket
107
165
  this.paired = false;
108
166
  this.pairingCode = null;
167
+ this.pairingAttempts = 0; // wrong-code counter for the current code
168
+ this.pairingCodeExpiresAt = 0; // absolute deadline; a reconnect reuses, never extends
169
+ this._pairingTimer = null; // TTL timer that expires the current code
170
+ this.maxPairingAttempts = opts.maxPairingAttempts ?? MAX_PAIRING_ATTEMPTS;
171
+ this.pairingCodeTtlMs = opts.pairingCodeTtlMs ?? PAIRING_CODE_TTL_MS;
109
172
  this.sessionToken = loadToken();
110
173
  this.pending = new Map(); // requestId → { entry, lane }
111
174
  this.requestTimeoutMs = opts.requestTimeoutMs ?? 25_000;
@@ -130,7 +193,12 @@ export class ExtensionBridge {
130
193
 
131
194
  listen() {
132
195
  return new Promise((resolve, reject) => {
133
- this.wss = new WebSocketServer({ host: this.host, port: this.port });
196
+ this.wss = new WebSocketServer({
197
+ host: this.host,
198
+ port: this.port,
199
+ // Reject browser-page origins at the handshake (see isAllowedOrigin).
200
+ verifyClient: (info) => isAllowedOrigin(info.origin),
201
+ });
134
202
 
135
203
  const onEarlyError = (err) => {
136
204
  this.wss.removeListener('listening', onListening);
@@ -140,7 +208,7 @@ export class ExtensionBridge {
140
208
  // `initialize` succeeds instead of getting EOF), but mark the bridge
141
209
  // unavailable so action calls return a clear, actionable message.
142
210
  this.portConflict = true;
143
- log(`Port ${this.port} is already in use — another Reply Wizard hub is`);
211
+ log(`Port ${this.port} is already in use, another Reply Wizard hub is`);
144
212
  log('probably already running. Starting without the WebSocket bridge;');
145
213
  log('action calls will report the conflict. Close the other hub, or set');
146
214
  log('RW_MCP_PORT to a free port if you intend to run more than one.');
@@ -166,6 +234,43 @@ export class ExtensionBridge {
166
234
  });
167
235
  }
168
236
 
237
+ // Issue a fresh pairing code: reset the wrong-attempt counter and arm a TTL
238
+ // timer that invalidates it if it isn't used in time.
239
+ //
240
+ // The expiry is recorded as an ABSOLUTE timestamp as well as a timer, because a
241
+ // reconnect now reuses a live code (see `_onConnection`) and the reuse must not push
242
+ // the deadline out. A rolling TTL would mean a client that reconnects every four
243
+ // minutes keeps one code alive forever, which is the opposite of what a TTL is for.
244
+ _setPairingCode(code) {
245
+ this.pairingCode = code;
246
+ this.pairingAttempts = 0;
247
+ this.pairingCodeExpiresAt = Date.now() + this.pairingCodeTtlMs;
248
+ clearTimeout(this._pairingTimer);
249
+ this._pairingTimer = setTimeout(() => {
250
+ this.pairingCode = null;
251
+ this.pairingCodeExpiresAt = 0;
252
+ clearPairingCode();
253
+ log('Pairing code expired; a new handshake is required to get a new one.');
254
+ }, this.pairingCodeTtlMs);
255
+ // Don't let the TTL timer keep the process (or tests) alive.
256
+ this._pairingTimer?.unref?.();
257
+ }
258
+
259
+ /** Is there a code a user could still usefully be typing? */
260
+ _pairingCodeIsLive() {
261
+ return Boolean(this.pairingCode) && Date.now() < this.pairingCodeExpiresAt;
262
+ }
263
+
264
+ // Invalidate the current pairing code and its TTL timer (on success, lockout,
265
+ // an expired-code reconnect, or shutdown).
266
+ _resetPairing() {
267
+ this.pairingCode = null;
268
+ this.pairingAttempts = 0;
269
+ this.pairingCodeExpiresAt = 0;
270
+ clearTimeout(this._pairingTimer);
271
+ this._pairingTimer = null;
272
+ }
273
+
169
274
  _onConnection(ws) {
170
275
  if (this.socket && this.socket.readyState === this.socket.OPEN) {
171
276
  log('Rejecting extra connection; one extension is already connected.');
@@ -174,14 +279,34 @@ export class ExtensionBridge {
174
279
  }
175
280
  this.socket = ws;
176
281
  this.paired = false;
177
- this.pairingCode = null;
282
+ // A LIVE pairing code survives the reconnect, deliberately.
283
+ //
284
+ // It used to be thrown away here and a new one minted on the next handshake, which
285
+ // meant the six digits the user was reading off a desktop toast went stale while they
286
+ // were typing them, and every reconnect fired another toast. The extension's service
287
+ // worker reconnects on its own schedule, so an unpaired user could watch three codes
288
+ // go by before entering one.
289
+ //
290
+ // Two properties make this safe rather than merely convenient, and both are tested:
291
+ // the deadline is NOT extended (see `_setPairingCode`), and the wrong-attempt counter
292
+ // is NOT reset. Carrying the counter is the load-bearing half: without it, closing and
293
+ // reopening the socket would hand an attacker another `maxPairingAttempts` guesses
294
+ // against the SAME code, over and over. Today's behaviour is safe only because the
295
+ // code changes each time, so preserving one without the other would be a regression.
296
+ if (!this._pairingCodeIsLive()) this._resetPairing();
178
297
  log('Extension connected. Waiting for handshake…');
179
298
 
180
299
  ws.on('message', (raw) => this._onMessage(raw));
181
300
  ws.on('close', () => {
182
301
  log('Extension disconnected.');
183
302
  this._failAll(new Error('Extension disconnected.'));
184
- if (this.socket === ws) { this.socket = null; this.paired = false; }
303
+ if (this.socket === ws) {
304
+ this.socket = null;
305
+ this.paired = false;
306
+ // Same rule as `_onConnection`: a code the user may still be typing outlives the
307
+ // socket it was minted for. An expired one is cleared here so nothing lingers.
308
+ if (!this._pairingCodeIsLive()) this._resetPairing();
309
+ }
185
310
  });
186
311
  ws.on('error', (e) => log('Socket error:', e && e.message));
187
312
  }
@@ -197,15 +322,24 @@ export class ExtensionBridge {
197
322
  this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION } });
198
323
  this._sendClients(); // sync current assistants to a freshly reconnected extension
199
324
  log('Reconnected with a valid session token (no pairing needed).');
325
+ } else if (this._pairingCodeIsLive()) {
326
+ // The code from before the reconnect is still good. Say so in the log and do NOT
327
+ // toast again: one code, one notification. The file is rewritten because it is a
328
+ // mirror rather than the source of truth, so this heals a deleted one.
329
+ writePairingCode(this.pairingCode);
330
+ const secondsLeft = Math.max(1, Math.round((this.pairingCodeExpiresAt - Date.now()) / 1000));
331
+ log(`Reconnected while unpaired; the existing code is still valid for ~${secondsLeft}s `
332
+ + `(${this.pairingAttempts}/${this.maxPairingAttempts} wrong attempts used).`);
333
+ this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
200
334
  } else {
201
- this.pairingCode = sixDigitCode();
335
+ this._setPairingCode(sixDigitCode());
202
336
  writePairingCode(this.pairingCode);
203
337
  try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ }
204
338
  log('');
205
339
  log(' ┌──────────────────────────────────────────────┐');
206
340
  log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
207
341
  log(' └──────────────────────────────────────────────┘');
208
- log(' Enter it in Reply Wizard → popup → AI client access.');
342
+ log(' Enter it in Reply Wizard → Settings → WhatsApp MCP.');
209
343
  log(' (A desktop notification with the code should also appear.)');
210
344
  log(` (Running in the background? Read it from ${pairingFile()})`);
211
345
  this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
@@ -214,27 +348,48 @@ export class ExtensionBridge {
214
348
  }
215
349
 
216
350
  if (msg.method === CONTROL.PAIRING_RESPONSE) {
217
- const ok = msg.params && msg.params.approved && this.pairingCode && msg.params.code === this.pairingCode;
351
+ // No active code (never issued, or already expired) → nothing to match.
352
+ if (!this.pairingCode) {
353
+ this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'expired' } });
354
+ log('Pairing response ignored: no active code (expired or not requested).');
355
+ return;
356
+ }
357
+ const ok = msg.params && msg.params.approved && msg.params.code === this.pairingCode;
218
358
  if (ok) {
219
359
  this.paired = true;
220
- this.sessionToken = randomUUID();
360
+ // 256-bit token (hex): matches the daemon's HTTP token strength, rather
361
+ // than randomUUID's ~122 bits of entropy (L1).
362
+ this.sessionToken = randomBytes(32).toString('hex');
221
363
  saveToken(this.sessionToken);
222
364
  clearPairingCode();
365
+ this._resetPairing();
223
366
  this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: this.sessionToken } });
224
367
  this._send({ method: CONTROL.AUTH_SUCCESS, params: {} });
225
368
  this._sendClients(); // sync current assistants right after pairing
226
369
  log('Pairing approved.');
227
370
  } else {
228
- // Tell the extension so it can show "incorrect code" instead of just
229
- // silently staying on "Pairing needed". A rejected code keeps the same
230
- // pairing code active so the user can retry without a new handshake.
231
- this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'invalid_code' } });
232
- log('Pairing rejected or wrong code.');
371
+ // Wrong code. Cap attempts to bound online brute-forcing: after the limit,
372
+ // invalidate the code entirely so a fresh handshake (and new code) is
373
+ // required. Below the limit, keep the same code active so a user who
374
+ // mistyped can retry without a new handshake.
375
+ this.pairingAttempts++;
376
+ if (this.pairingAttempts >= this.maxPairingAttempts) {
377
+ this._resetPairing();
378
+ clearPairingCode();
379
+ this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'too_many_attempts' } });
380
+ log(`Pairing locked out after ${this.maxPairingAttempts} wrong attempts; code invalidated.`);
381
+ } else {
382
+ this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'invalid_code' } });
383
+ log(`Pairing rejected or wrong code (${this.pairingAttempts}/${this.maxPairingAttempts}).`);
384
+ }
233
385
  }
234
386
  return;
235
387
  }
236
388
 
237
389
  if (msg.method === CONTROL.PONG) return;
390
+ // Extension heartbeat (keeps its MV3 service worker alive). Echo a PONG so the
391
+ // round-trip also counts as inbound activity on the extension's socket.
392
+ if (msg.method === CONTROL.PING) { this._send({ method: CONTROL.PONG }); return; }
238
393
 
239
394
  // Action result correlation: settle the caller, free its lane slot, pump the lane.
240
395
  if (msg.id && this.pending.has(msg.id)) {
@@ -332,7 +487,7 @@ export class ExtensionBridge {
332
487
  _send(obj) {
333
488
  // Never throw out of a send: if the socket is closing mid-write, socket.send can
334
489
  // throw and would otherwise unwind _dispatch, leaking a lane slot until timeout.
335
- // Swallowing here is safe — the per-action timeout and _failAll(on-disconnect)
490
+ // Swallowing here is safe: the per-action timeout and _failAll(on-disconnect)
336
491
  // both recover the in-flight entry.
337
492
  try {
338
493
  if (this.socket && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(obj));
@@ -367,6 +522,7 @@ export class ExtensionBridge {
367
522
  }
368
523
 
369
524
  close() {
525
+ this._resetPairing();
370
526
  this._failAll(new Error('Hub shutting down.'));
371
527
  if (this.wss) this.wss.close();
372
528
  }