replywizard-whatsapp-mcp 0.6.3 → 0.7.0
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 +43 -3
- package/package.json +8 -3
- package/src/bundleEntry.js +14 -0
- package/src/connector.js +56 -7
- package/src/daemon.js +68 -19
- package/src/hostVersion.js +18 -0
- package/src/protocol.js +10 -1
- package/src/remote.js +54 -13
- package/src/runtime.js +40 -0
- package/src/wsServer.js +213 -40
package/README.md
CHANGED
|
@@ -67,7 +67,38 @@ extension** (the hub only sees tool arguments and results).
|
|
|
67
67
|
Published to npm as [`replywizard-whatsapp-mcp`](https://www.npmjs.com/package/replywizard-whatsapp-mcp).
|
|
68
68
|
You don't install anything by hand, your AI client runs it via `npx` (requires Node.js 18+).
|
|
69
69
|
|
|
70
|
-
###
|
|
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
|
|
71
102
|
|
|
72
103
|
Add to `claude_desktop_config.json`:
|
|
73
104
|
|
|
@@ -117,6 +148,10 @@ the entry in the editor's own MCP panel as well.
|
|
|
117
148
|
|
|
118
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.
|
|
119
150
|
|
|
151
|
+
**Mutual authentication (0.7.0, prepared 2026-11-19, not yet published).** Once paired, the extension no longer sends its session token to the socket. It sends a random nonce and a key id; the daemon must prove it holds the token with an HMAC-SHA256 over both sides' nonces, and only then does the extension prove it back. A process that took the port before the daemon learns nothing it can use and gets no answers. Pairing itself is unchanged. For one release the daemon still accepts the older extension's token handshake, and an extension talking to a daemon older than 0.7.0 still connects but shows the "companion host is out of date" notice.
|
|
152
|
+
|
|
153
|
+
**Pairing hardened (0.6.4, published 2026-11-13).** Only the Chrome Web Store and Edge Add-ons extension ids may connect (plus any named in `REPLYWIZARD_EXTENSION_IDS`), and a handshake with no `Origin` is refused. New pairing codes are limited to three in ten minutes per daemon: before, a client could lock a code out and get a new one thousands of times a second, which made pairing guessable in about 45 seconds. `/healthz` checks the `Host` header like `/mcp` does, so a page on a rebound name cannot read it. Two `replywizard --remote` processes refreshing at once share one lock beside the credentials file, so they no longer spend the same refresh token and sign you out.
|
|
154
|
+
|
|
120
155
|
**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.
|
|
121
156
|
|
|
122
157
|
**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`.
|
|
@@ -251,7 +286,9 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
|
|
|
251
286
|
}
|
|
252
287
|
```
|
|
253
288
|
|
|
254
|
-
> From source: `node /abs/path/mcp-host/src/connector.js` (or
|
|
289
|
+
> From source: `node /abs/path/mcp-host/src/connector.js` (or `node …/src/connector.js daemon`, or
|
|
290
|
+
> `…/daemon.js`, to run the daemon directly). The connector starts the daemon as itself with the
|
|
291
|
+
> `daemon` subcommand, so the same file works unbundled and as the one-file `.mcpb` bundle.
|
|
255
292
|
|
|
256
293
|
### Environment variables
|
|
257
294
|
|
|
@@ -261,11 +298,12 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
|
|
|
261
298
|
| `RW_MCP_HTTP_PORT` | `7870` | Daemon HTTP (client) port. |
|
|
262
299
|
| `RW_MCP_IDLE_MS` | `1800000` | Daemon exits after this long with no sessions (`0` disables). |
|
|
263
300
|
| `RW_MCP_STALE_SESSION_MS` | `600000` | Reap sessions silent this long (client crashed without a clean disconnect). |
|
|
301
|
+
| `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. |
|
|
264
302
|
|
|
265
303
|
### Auth token
|
|
266
304
|
|
|
267
305
|
The daemon generates a bearer token on first start at `~/.replywizard-mcp/daemon-token.json` (mode
|
|
268
|
-
`600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz`
|
|
306
|
+
`600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz` needs no token but, from 0.6.4, a loopback `Host` header.
|
|
269
307
|
The connector reads it automatically. **To revoke**, delete that file (the daemon mints a new one on
|
|
270
308
|
next start): existing clients must pick up the new token.
|
|
271
309
|
|
|
@@ -323,6 +361,8 @@ client. Printed, the two tell themselves apart.
|
|
|
323
361
|
|
|
324
362
|
- Binds to `127.0.0.1` only.
|
|
325
363
|
- No tool runs until the pairing code is confirmed in the extension.
|
|
364
|
+
- After pairing, the session token never travels: each reconnect is a challenge and HMAC-SHA256 proof in both directions (0.7.0).
|
|
365
|
+
- Only the Reply Wizard store extension ids may open the extension socket (0.6.4), and at most three new pairing codes are minted in ten minutes.
|
|
326
366
|
- **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
|
|
327
367
|
`send_message` call is sent only when you press Send in WhatsApp Web; no tool edits or deletes a
|
|
328
368
|
message.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "replywizard-whatsapp-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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/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
|
|
144
|
-
const child = spawn(
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
329
|
-
|
|
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
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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 =
|
|
275
|
-
const staleSessionMs =
|
|
276
|
-
const sweepIntervalMs =
|
|
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: () => {
|
|
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
|
-
|
|
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
|
-
|
|
329
|
+
settle(false);
|
|
330
|
+
if (!inProcess) process.exit(0);
|
|
331
|
+
return;
|
|
294
332
|
}
|
|
295
|
-
|
|
333
|
+
say('HTTP server error:', (err && err.message) || err);
|
|
296
334
|
});
|
|
297
335
|
|
|
298
336
|
daemon.listen(() => {
|
|
299
|
-
|
|
300
|
-
if (bridge.portConflict)
|
|
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
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/hostVersion.js
CHANGED
|
@@ -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/protocol.js
CHANGED
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
//
|
|
7
7
|
// Keep the EXPORTED VALUES below byte-identical to the extension's copy.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
// 2 (mcp-host 0.7.0, audit 2026-11-19 mcp-1): a paired extension authenticates with
|
|
10
|
+
// auth_hello / auth_challenge / auth_proof, HMAC-SHA256 over the session token both ways, and
|
|
11
|
+
// the token no longer travels. Pairing (the first issue of a token) is unchanged.
|
|
12
|
+
export const PROTOCOL_VERSION = 2;
|
|
10
13
|
|
|
11
14
|
export const PAGE_REQ = 'RW_MCP_REQ';
|
|
12
15
|
export const PAGE_RESP = 'RW_MCP_RESP';
|
|
@@ -81,6 +84,9 @@ export const CONTROL = Object.freeze({
|
|
|
81
84
|
PAIRING_COMPLETE: 'pairing_complete',
|
|
82
85
|
PAIRING_FAILED: 'pairing_failed',
|
|
83
86
|
AUTH_SUCCESS: 'auth_success',
|
|
87
|
+
AUTH_HELLO: 'auth_hello',
|
|
88
|
+
AUTH_CHALLENGE: 'auth_challenge',
|
|
89
|
+
AUTH_PROOF: 'auth_proof',
|
|
84
90
|
CLIENTS_UPDATE: 'clients_update',
|
|
85
91
|
PING: 'ping',
|
|
86
92
|
PONG: 'pong',
|
|
@@ -93,4 +99,7 @@ export const STORAGE_KEYS = Object.freeze({
|
|
|
93
99
|
PORT: 'rw_mcp_port',
|
|
94
100
|
SESSION_TOKEN: 'rw_mcp_session_token',
|
|
95
101
|
SESSION_ID: 'rw_mcp_session_id',
|
|
102
|
+
// True once the hub holding this token has proved it by HMAC; from then on the extension
|
|
103
|
+
// never falls back to sending the raw token (no downgrade). Cleared with the token.
|
|
104
|
+
HOST_PROVED: 'rw_mcp_host_proved',
|
|
96
105
|
});
|
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
|
|
176
|
-
if (!
|
|
177
|
-
if (!force &&
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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
|
@@ -3,8 +3,9 @@
|
|
|
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.
|
|
5
5
|
//
|
|
6
|
-
// Auth flow:
|
|
7
|
-
// • extension sends `
|
|
6
|
+
// Auth flow (see MUTUAL AUTHENTICATION below for the 0.7 exchange that replaced the first step):
|
|
7
|
+
// • a paired extension sends `auth_hello`; both sides prove the token by HMAC and it never
|
|
8
|
+
// travels. An extension older than 0.7's protocol sends `handshake { session_token }`.
|
|
8
9
|
// • if the token matches the persisted one → `auth_success` (no prompt). This is
|
|
9
10
|
// what makes reconnects seamless.
|
|
10
11
|
// • otherwise the hub prints a one-time 6-digit code to STDERR (stdout is reserved
|
|
@@ -22,7 +23,7 @@
|
|
|
22
23
|
// Self-contained: depends only on `ws`, node builtins, and ./protocol.js.
|
|
23
24
|
|
|
24
25
|
import { WebSocketServer } from 'ws';
|
|
25
|
-
import { randomBytes, randomUUID } from 'node:crypto';
|
|
26
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
26
27
|
import { platform } from 'node:os';
|
|
27
28
|
import { join } from 'node:path';
|
|
28
29
|
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
|
@@ -87,6 +88,51 @@ function saveTokens(tokens) {
|
|
|
87
88
|
return reason;
|
|
88
89
|
}
|
|
89
90
|
|
|
91
|
+
/*
|
|
92
|
+
* MUTUAL AUTHENTICATION (audit 2026-11-19 mcp-1 (b), mcp-host 0.7.0).
|
|
93
|
+
*
|
|
94
|
+
* Until 0.7 the extension sent its raw session token in `handshake` to whatever answered on
|
|
95
|
+
* 127.0.0.1:<port>, and trusted any `auth_success` that came back. A process that bound the
|
|
96
|
+
* port before this daemon received the token and could then pose as the browser here.
|
|
97
|
+
*
|
|
98
|
+
* Now, once paired, neither side sends the token and neither trusts a peer that cannot prove
|
|
99
|
+
* it holds it:
|
|
100
|
+
* extension -> auth_hello { protocol, client_nonce, key_id }
|
|
101
|
+
* hub -> auth_challenge { protocol, server_nonce, proof: HMAC(token, 'host|' + client_nonce + '|' + server_nonce) }
|
|
102
|
+
* extension -> auth_proof { proof: HMAC(token, 'ext|' + server_nonce + '|' + client_nonce) }
|
|
103
|
+
* hub -> auth_success
|
|
104
|
+
* `key_id` (HMAC(token, 'rw-mcp-key-id'), 128 bits) only says WHICH of the remembered tokens
|
|
105
|
+
* to use; it proves nothing and the hub never accepts it as proof. An unknown key id starts an
|
|
106
|
+
* ordinary pairing, so a hub that lost its session file still recovers the way it always did.
|
|
107
|
+
* Pairing itself (the first issue of a token) is unchanged.
|
|
108
|
+
*
|
|
109
|
+
* The compatibility window, and the one switch that closes it: an extension older than this
|
|
110
|
+
* protocol still sends `handshake { session_token }`. While this is true that is accepted as
|
|
111
|
+
* before; set it to false in a later release and such an extension is told `upgrade_required`.
|
|
112
|
+
*/
|
|
113
|
+
export const LEGACY_TOKEN_AUTH_ACCEPTED = true;
|
|
114
|
+
|
|
115
|
+
const NONCE_RE = /^[0-9a-f]{64}$/;
|
|
116
|
+
const KEY_ID_RE = /^[0-9a-f]{32}$/;
|
|
117
|
+
|
|
118
|
+
/** HMAC-SHA256(token, `${role}|${first}|${second}`), hex. Same construction as the extension's. */
|
|
119
|
+
export function authProof(token, role, first, second) {
|
|
120
|
+
return createHmac('sha256', String(token)).update(`${role}|${first}|${second}`).digest('hex');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Which token a hello means, without revealing it: HMAC(token, 'rw-mcp-key-id'), 32 hex. */
|
|
124
|
+
export function keyIdFor(token) {
|
|
125
|
+
return createHmac('sha256', String(token)).update('rw-mcp-key-id').digest('hex').slice(0, 32);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Constant-time equality for two strings of attacker-chosen content. */
|
|
129
|
+
export function safeEqual(a, b) {
|
|
130
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
131
|
+
const x = Buffer.from(a, 'utf8');
|
|
132
|
+
const y = Buffer.from(b, 'utf8');
|
|
133
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
134
|
+
}
|
|
135
|
+
|
|
90
136
|
// When the daemon runs detached (spawned by the connector, stderr → /dev/null), the
|
|
91
137
|
// printed pairing code is invisible. Mirror it to a file so a first-time user can read
|
|
92
138
|
// it (`cat ~/.replywizard-mcp/pairing-code.txt`). Cleared once pairing succeeds.
|
|
@@ -108,20 +154,44 @@ const MAX_PAIRING_ATTEMPTS = 5;
|
|
|
108
154
|
// screen can't be brute-forced indefinitely.
|
|
109
155
|
const PAIRING_CODE_TTL_MS = 5 * 60_000;
|
|
110
156
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
//
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
157
|
+
/**
|
|
158
|
+
* The extension ids allowed to dial this hub: the Chrome Web Store build (an unpacked build
|
|
159
|
+
* resolves to the same id through the manifest `key`) and the Edge Add-ons build, plus any ids
|
|
160
|
+
* named in REPLYWIZARD_EXTENSION_IDS (comma or space separated) for a local test build.
|
|
161
|
+
*/
|
|
162
|
+
export const STORE_EXTENSION_IDS = Object.freeze([
|
|
163
|
+
'hohbipdklpppfhngiekmebefnocpgplp', // Chrome Web Store (src/utils.js CWS_ID)
|
|
164
|
+
'pnaodlbifmohggdcjapcfpmmllhakbmg', // Edge Add-ons (src/utils.js EDGE_ID)
|
|
165
|
+
]);
|
|
166
|
+
|
|
167
|
+
export function allowedExtensionOrigins(env = process.env) {
|
|
168
|
+
const extra = String((env && env.REPLYWIZARD_EXTENSION_IDS) || '')
|
|
169
|
+
.split(/[\s,]+/).map((s) => s.trim()).filter((s) => /^[a-p]{32}$/.test(s));
|
|
170
|
+
return new Set([...STORE_EXTENSION_IDS, ...extra].map((id) => `chrome-extension://${id}`));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Decide whether a WebSocket handshake's Origin is allowed. WebSocket is NOT subject to
|
|
174
|
+
// same-origin policy, so any page, or any other extension, could otherwise dial
|
|
175
|
+
// ws://127.0.0.1:<port> and guess pairing codes. The legitimate client is the Reply Wizard
|
|
176
|
+
// extension's MV3 service worker, and Chrome always sends `Origin: chrome-extension://<id>`
|
|
177
|
+
// on its WebSocket handshake, so only our own ids pass. A MISSING Origin is refused too
|
|
178
|
+
// (review 2026-11-13): the real client always sends one, and the only thing that does not is
|
|
179
|
+
// a local process, which had no business racing for the pairing slot. Exported for tests.
|
|
180
|
+
export function isAllowedOrigin(origin, allowed = allowedExtensionOrigins()) {
|
|
181
|
+
if (!origin || typeof origin !== 'string') return false;
|
|
182
|
+
return allowed.has(origin);
|
|
123
183
|
}
|
|
124
184
|
|
|
185
|
+
/**
|
|
186
|
+
* How many NEW pairing codes one daemon process mints in a window. Each code takes at most
|
|
187
|
+
* `MAX_PAIRING_ATTEMPTS` guesses, so without this a client could lock a code out and get a new
|
|
188
|
+
* one on the same socket thousands of times a second (measured 4,596 codes/s, pairing in about
|
|
189
|
+
* 45 s), each with a desktop toast. Three codes in ten minutes is fifteen guesses: plenty for a
|
|
190
|
+
* person who mistypes, and about 1.3 years of expected guessing for a script.
|
|
191
|
+
*/
|
|
192
|
+
export const PAIRING_CODES_PER_WINDOW = 3;
|
|
193
|
+
export const PAIRING_CODE_WINDOW_MS = 10 * 60_000;
|
|
194
|
+
|
|
125
195
|
// Surface the pairing code as an OS desktop notification so a non-technical user
|
|
126
196
|
// sees it WITHOUT a terminal (the connector launches us in the background, where
|
|
127
197
|
// stderr is invisible). This is a valid out-of-band channel: only someone at the
|
|
@@ -218,6 +288,11 @@ export class ExtensionBridge {
|
|
|
218
288
|
this._pairingTimer = null; // TTL timer that expires the current code
|
|
219
289
|
this.maxPairingAttempts = opts.maxPairingAttempts ?? MAX_PAIRING_ATTEMPTS;
|
|
220
290
|
this.pairingCodeTtlMs = opts.pairingCodeTtlMs ?? PAIRING_CODE_TTL_MS;
|
|
291
|
+
this.pairingCodesPerWindow = opts.pairingCodesPerWindow ?? PAIRING_CODES_PER_WINDOW;
|
|
292
|
+
this.pairingCodeWindowMs = opts.pairingCodeWindowMs ?? PAIRING_CODE_WINDOW_MS;
|
|
293
|
+
this._codeMints = []; // when each recent code was minted, for the per-process limit
|
|
294
|
+
this._lastCodeLockedOut = false; // the previous code died of wrong guesses, not of age
|
|
295
|
+
this.allowedOrigins = opts.allowedOrigins ?? allowedExtensionOrigins();
|
|
221
296
|
this.sessionTokens = loadTokens(); // newest first; `sessionToken` below is the head
|
|
222
297
|
// The last persistence failure, or null. Reported on the wire and on /healthz rather than
|
|
223
298
|
// only logged, because the log goes nowhere for a daemon the connector spawned detached.
|
|
@@ -253,7 +328,7 @@ export class ExtensionBridge {
|
|
|
253
328
|
host: this.host,
|
|
254
329
|
port: this.port,
|
|
255
330
|
// Reject browser-page origins at the handshake (see isAllowedOrigin).
|
|
256
|
-
verifyClient: (info) => isAllowedOrigin(info.origin),
|
|
331
|
+
verifyClient: (info) => isAllowedOrigin(info.origin, this.allowedOrigins),
|
|
257
332
|
});
|
|
258
333
|
|
|
259
334
|
const onEarlyError = (err) => {
|
|
@@ -344,9 +419,11 @@ export class ExtensionBridge {
|
|
|
344
419
|
* actually changes, so an ordinary reconnect (already the head) costs no disk at all.
|
|
345
420
|
*/
|
|
346
421
|
_acceptToken(token) {
|
|
347
|
-
|
|
422
|
+
let at = -1;
|
|
423
|
+
this.sessionTokens.forEach((t, i) => { if (safeEqual(t, token) && at === -1) at = i; });
|
|
348
424
|
if (at === -1) return false;
|
|
349
425
|
if (at > 0) {
|
|
426
|
+
token = this.sessionTokens[at];
|
|
350
427
|
this.sessionTokens = [token, ...this.sessionTokens.filter((t) => t !== token)];
|
|
351
428
|
this.persistError = saveTokens(this.sessionTokens);
|
|
352
429
|
}
|
|
@@ -361,6 +438,7 @@ export class ExtensionBridge {
|
|
|
361
438
|
}
|
|
362
439
|
this.socket = ws;
|
|
363
440
|
this.paired = false;
|
|
441
|
+
this._challenge = null; // a challenge belongs to the socket it was issued on
|
|
364
442
|
// A LIVE pairing code survives the reconnect, deliberately.
|
|
365
443
|
//
|
|
366
444
|
// It used to be thrown away here and a new one minted on the next handshake, which
|
|
@@ -385,6 +463,7 @@ export class ExtensionBridge {
|
|
|
385
463
|
if (this.socket === ws) {
|
|
386
464
|
this.socket = null;
|
|
387
465
|
this.paired = false;
|
|
466
|
+
this._challenge = null;
|
|
388
467
|
// Same rule as `_onConnection`: a code the user may still be typing outlives the
|
|
389
468
|
// socket it was minted for. An expired one is cleared here so nothing lingers.
|
|
390
469
|
if (!this._pairingCodeIsLive()) this._resetPairing();
|
|
@@ -397,34 +476,24 @@ export class ExtensionBridge {
|
|
|
397
476
|
let msg;
|
|
398
477
|
try { msg = JSON.parse(raw.toString()); } catch { log('Dropped non-JSON message'); return; }
|
|
399
478
|
|
|
479
|
+
if (msg.method === CONTROL.AUTH_HELLO) { this._onAuthHello(msg.params || {}); return; }
|
|
480
|
+
if (msg.method === CONTROL.AUTH_PROOF) { this._onAuthProof(msg.params || {}); return; }
|
|
481
|
+
|
|
400
482
|
if (msg.method === CONTROL.HANDSHAKE) {
|
|
401
483
|
const token = msg.params && msg.params.session_token;
|
|
484
|
+
if (token && !LEGACY_TOKEN_AUTH_ACCEPTED) {
|
|
485
|
+
// The window is closed: an extension that still sends its token raw must update.
|
|
486
|
+
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'upgrade_required' } });
|
|
487
|
+
this._refuse('upgrade_required');
|
|
488
|
+
log('Refused a raw session token: this extension predates mutual authentication.');
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
402
491
|
if (token && this._acceptToken(token)) {
|
|
403
492
|
this.paired = true;
|
|
404
|
-
this.
|
|
405
|
-
|
|
406
|
-
log('Reconnected with a valid session token (no pairing needed).');
|
|
407
|
-
} else if (this._pairingCodeIsLive()) {
|
|
408
|
-
// The code from before the reconnect is still good. Say so in the log and do NOT
|
|
409
|
-
// toast again: one code, one notification. The file is rewritten because it is a
|
|
410
|
-
// mirror rather than the source of truth, so this heals a deleted one.
|
|
411
|
-
writePairingCode(this.pairingCode);
|
|
412
|
-
const secondsLeft = Math.max(1, Math.round((this.pairingCodeExpiresAt - Date.now()) / 1000));
|
|
413
|
-
log(`Reconnected while unpaired; the existing code is still valid for ~${secondsLeft}s `
|
|
414
|
-
+ `(${this.pairingAttempts}/${this.maxPairingAttempts} wrong attempts used).`);
|
|
415
|
-
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
493
|
+
this._sendAuthSuccess();
|
|
494
|
+
log('Reconnected with a valid session token (legacy handshake, no pairing needed).');
|
|
416
495
|
} else {
|
|
417
|
-
this.
|
|
418
|
-
writePairingCode(this.pairingCode);
|
|
419
|
-
try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ }
|
|
420
|
-
log('');
|
|
421
|
-
log(' ┌──────────────────────────────────────────────┐');
|
|
422
|
-
log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
|
|
423
|
-
log(' └──────────────────────────────────────────────┘');
|
|
424
|
-
log(' Enter it in Reply Wizard → Settings → WhatsApp MCP.');
|
|
425
|
-
log(' (A desktop notification with the code should also appear.)');
|
|
426
|
-
log(` (Running in the background? Read it from ${pairingFile()})`);
|
|
427
|
-
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
496
|
+
this._startPairing();
|
|
428
497
|
}
|
|
429
498
|
return;
|
|
430
499
|
}
|
|
@@ -446,6 +515,9 @@ export class ExtensionBridge {
|
|
|
446
515
|
this.persistError = saveTokens(this.sessionTokens);
|
|
447
516
|
clearPairingCode();
|
|
448
517
|
this._resetPairing();
|
|
518
|
+
// A completed pairing is not an attack, so it does not count against the next browser.
|
|
519
|
+
this._codeMints = [];
|
|
520
|
+
this._lastCodeLockedOut = false;
|
|
449
521
|
// `session_persisted: false` says "you are paired now, and this will not survive a
|
|
450
522
|
// restart". The extension shows it; without it the only trace is a log nobody reads
|
|
451
523
|
// and a code that comes back tomorrow for no visible reason.
|
|
@@ -462,6 +534,7 @@ export class ExtensionBridge {
|
|
|
462
534
|
this.pairingAttempts++;
|
|
463
535
|
if (this.pairingAttempts >= this.maxPairingAttempts) {
|
|
464
536
|
this._resetPairing();
|
|
537
|
+
this._lastCodeLockedOut = true;
|
|
465
538
|
clearPairingCode();
|
|
466
539
|
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'too_many_attempts' } });
|
|
467
540
|
log(`Pairing locked out after ${this.maxPairingAttempts} wrong attempts; code invalidated.`);
|
|
@@ -487,6 +560,106 @@ export class ExtensionBridge {
|
|
|
487
560
|
}
|
|
488
561
|
}
|
|
489
562
|
|
|
563
|
+
/** No usable credential on this socket: reuse a live code, or mint one within the limits. */
|
|
564
|
+
_startPairing() {
|
|
565
|
+
if (this._pairingCodeIsLive()) {
|
|
566
|
+
// The code from before the reconnect is still good. Say so in the log and do NOT
|
|
567
|
+
// toast again: one code, one notification. The file is rewritten because it is a
|
|
568
|
+
// mirror rather than the source of truth, so this heals a deleted one.
|
|
569
|
+
writePairingCode(this.pairingCode);
|
|
570
|
+
const secondsLeft = Math.max(1, Math.round((this.pairingCodeExpiresAt - Date.now()) / 1000));
|
|
571
|
+
log(`Reconnected while unpaired; the existing code is still valid for ~${secondsLeft}s `
|
|
572
|
+
+ `(${this.pairingAttempts}/${this.maxPairingAttempts} wrong attempts used).`);
|
|
573
|
+
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
574
|
+
} else {
|
|
575
|
+
const now = Date.now();
|
|
576
|
+
this._codeMints = this._codeMints.filter((t) => now - t < this.pairingCodeWindowMs);
|
|
577
|
+
if (this._codeMints.length >= this.pairingCodesPerWindow) {
|
|
578
|
+
// The socket stays open on purpose: closing it makes the extension reconnect and ask
|
|
579
|
+
// again on its backoff, which clears the error it would otherwise show.
|
|
580
|
+
const retryAfterS = Math.max(1, Math.ceil((this._codeMints[0] + this.pairingCodeWindowMs - now) / 1000));
|
|
581
|
+
this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'rate_limited', retry_after_s: retryAfterS } });
|
|
582
|
+
log(`Pairing refused: ${this.pairingCodesPerWindow} codes were issued in the last `
|
|
583
|
+
+ `${Math.round(this.pairingCodeWindowMs / 60_000)} minutes. Try again in ~${retryAfterS}s.`);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
// A code that replaces one locked out by wrong guesses is not announced unless it is
|
|
587
|
+
// the first of the window: that is the brute-force path, and each toast was a process
|
|
588
|
+
// launch on the desktop. A code that replaces an EXPIRED one is announced, because a
|
|
589
|
+
// person who came back after five minutes needs to see it, and expiry cannot be sped up.
|
|
590
|
+
const announce = this._codeMints.length === 0 || !this._lastCodeLockedOut;
|
|
591
|
+
this._codeMints.push(now);
|
|
592
|
+
this._lastCodeLockedOut = false;
|
|
593
|
+
this._setPairingCode(sixDigitCode());
|
|
594
|
+
writePairingCode(this.pairingCode);
|
|
595
|
+
if (announce) { try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ } }
|
|
596
|
+
log('');
|
|
597
|
+
log(' ┌──────────────────────────────────────────────┐');
|
|
598
|
+
log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
|
|
599
|
+
log(' └──────────────────────────────────────────────┘');
|
|
600
|
+
log(' Enter it in Reply Wizard → Settings → WhatsApp MCP.');
|
|
601
|
+
log(' (A desktop notification with the code should also appear.)');
|
|
602
|
+
log(` (Running in the background? Read it from ${pairingFile()})`);
|
|
603
|
+
this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
_sendAuthSuccess() {
|
|
608
|
+
// Row 48: the extension cannot otherwise tell a current bridge from a stale one.
|
|
609
|
+
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion(), session_persisted: !this.persistError } });
|
|
610
|
+
this._sendClients(); // sync current assistants to a freshly authenticated extension
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Close the current socket for a failed proof; the code tells the extension why. */
|
|
614
|
+
_refuse(reason) {
|
|
615
|
+
this._challenge = null;
|
|
616
|
+
this.paired = false;
|
|
617
|
+
try { if (this.socket && typeof this.socket.close === 'function') this.socket.close(1008, reason); } catch { /* noop */ }
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Step 1 of mutual authentication: prove to the extension that this hub holds its token,
|
|
622
|
+
* without sending the token. Computed synchronously, so a challenge always reaches the
|
|
623
|
+
* extension before the answer to any `ping` it sent behind its hello; that ordering is how
|
|
624
|
+
* an extension tells this hub from an older one that ignores the hello.
|
|
625
|
+
*/
|
|
626
|
+
_onAuthHello(p) {
|
|
627
|
+
this._challenge = null;
|
|
628
|
+
this.paired = false; // a hello asks for fresh proof, whatever this socket did before
|
|
629
|
+
if (!NONCE_RE.test(String(p.client_nonce || ''))) { this._refuse('bad_hello'); return; }
|
|
630
|
+
const keyId = String(p.key_id || '');
|
|
631
|
+
const token = KEY_ID_RE.test(keyId) ? this.sessionTokens.find((t) => safeEqual(keyIdFor(t), keyId)) : null;
|
|
632
|
+
if (!token) {
|
|
633
|
+
// Not a token this machine remembers (a reinstall, a deleted session file): pair again.
|
|
634
|
+
this.paired = false;
|
|
635
|
+
this._startPairing();
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const serverNonce = randomBytes(32).toString('hex');
|
|
639
|
+
this._challenge = { token, clientNonce: p.client_nonce, serverNonce };
|
|
640
|
+
this._send({
|
|
641
|
+
method: CONTROL.AUTH_CHALLENGE,
|
|
642
|
+
params: { protocol: PROTOCOL_VERSION, server_nonce: serverNonce, proof: authProof(token, 'host', p.client_nonce, serverNonce) },
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Step 2: the extension proves it holds the token. Anything else closes the socket. */
|
|
647
|
+
_onAuthProof(p) {
|
|
648
|
+
const ch = this._challenge;
|
|
649
|
+
this._challenge = null;
|
|
650
|
+
if (!ch) { this._refuse('no_challenge'); return; }
|
|
651
|
+
const expected = authProof(ch.token, 'ext', ch.serverNonce, ch.clientNonce);
|
|
652
|
+
if (!safeEqual(String(p.proof || ''), expected)) {
|
|
653
|
+
this._refuse('auth_failed');
|
|
654
|
+
log('Refused an extension that could not prove its session token.');
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
this._acceptToken(ch.token);
|
|
658
|
+
this.paired = true;
|
|
659
|
+
this._sendAuthSuccess();
|
|
660
|
+
log('Reconnected; both sides proved the session token (no pairing needed).');
|
|
661
|
+
}
|
|
662
|
+
|
|
490
663
|
/**
|
|
491
664
|
* Forward an action to the extension and await the result. Scheduled in a lane
|
|
492
665
|
* (read vs value) with bounded concurrency + per-lane backpressure; the per-action
|