replywizard-whatsapp-mcp 0.3.1 → 0.3.3
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 +23 -1
- package/package.json +1 -1
- package/src/cli.js +17 -0
- package/src/connector.js +76 -4
- package/src/daemon.js +10 -3
- package/src/daemonAuth.js +15 -13
- package/src/protocol.js +24 -0
- package/src/stateStore.js +66 -0
- package/src/tools.js +3 -1
- package/src/wsServer.js +89 -18
package/README.md
CHANGED
|
@@ -251,12 +251,33 @@ Two things do **not** change on reuse, and each is tested:
|
|
|
251
251
|
|
|
252
252
|
A code is still destroyed immediately on a successful pairing, on lockout, and on expiry.
|
|
253
253
|
|
|
254
|
+
**More than one browser can stay paired, since 0.3.2.** The session file held a single token
|
|
255
|
+
until then, and the hub accepts one extension socket at a time, so somebody running two Chrome
|
|
256
|
+
profiles (or Chrome and Edge) had each pairing invalidate the other's: whichever browser took
|
|
257
|
+
the socket next was asked for a fresh six-digit code, and neither was doing anything wrong. Up
|
|
258
|
+
to **five** browsers now stay paired at once. The least recently used is dropped when a sixth
|
|
259
|
+
pairs, and a successful reconnect moves that browser to the front, so the ones actually in use
|
|
260
|
+
are the ones that survive. Each token is still 256 bits, still minted only by a completed
|
|
261
|
+
pairing, and still only ever compared.
|
|
262
|
+
|
|
263
|
+
**If the hub cannot SAVE the pairing, it now says so.** Before 0.3.2 a failed write was a line
|
|
264
|
+
on a stderr the daemon does not have (the connector spawns it detached), so an unwritable or
|
|
265
|
+
full home directory produced a pairing that worked until the daemon restarted and was then
|
|
266
|
+
demanded again, for ever, with nothing said anywhere. Writes are atomic and read back before
|
|
267
|
+
they count, the extension is told on the handshake (`session_persisted: false`) and puts a
|
|
268
|
+
sentence on the MCP tab, and `replywizard status` prints both the reason and the directory it
|
|
269
|
+
is using. That directory matters on its own: the daemon inherits the environment of whichever
|
|
270
|
+
client started it, so a sandboxed editor (flatpak, snap) gives its daemon a different `HOME`
|
|
271
|
+
and therefore a different session file, and the pairing it makes is invisible to every other
|
|
272
|
+
client. Printed, the two tell themselves apart.
|
|
273
|
+
|
|
254
274
|
## Security
|
|
255
275
|
|
|
256
276
|
- Binds to `127.0.0.1` only.
|
|
257
277
|
- No tool runs until the pairing code is confirmed in the extension.
|
|
258
278
|
- **Read + value tools only**: v1 has no send/modify capability.
|
|
259
|
-
-
|
|
279
|
+
- Session tokens are stored at `~/.replywizard-mcp/session.json` (mode 600), at most five,
|
|
280
|
+
newest first. Override the directory with `RW_MCP_STATE_DIR`.
|
|
260
281
|
|
|
261
282
|
## Troubleshooting
|
|
262
283
|
|
|
@@ -264,6 +285,7 @@ A code is still destroyed immediately on a successful pairing, on lockout, and o
|
|
|
264
285
|
|---------|-----|
|
|
265
286
|
| `Reply Wizard extension is not connected` | Open WhatsApp Web and enable AI access in the popup. |
|
|
266
287
|
| `Not paired yet` | Enter the 6-digit code (printed to the hub's stderr) in the popup. |
|
|
288
|
+
| It asks for a code again and again | Run `replywizard status`. A `WARNING: this daemon cannot save its state` line means the state directory is unwritable or full. Otherwise compare the `state:` line across your AI clients: a sandboxed editor gives its daemon a different `HOME`, so it keeps its own session file. |
|
|
267
289
|
| `No WhatsApp Web tab is open` | A read/value tool needs an open, logged-in WhatsApp Web tab. |
|
|
268
290
|
| 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). |
|
|
269
291
|
| 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). |
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -336,6 +336,8 @@ export async function status(deps = {}) {
|
|
|
336
336
|
paired: !!body.paired,
|
|
337
337
|
sessions: body.sessions || 0,
|
|
338
338
|
tokenPresent: !!(deps.token !== undefined ? deps.token : readToken()),
|
|
339
|
+
stateDir: body.stateDir || null,
|
|
340
|
+
persistError: body.persistError || null,
|
|
339
341
|
};
|
|
340
342
|
} catch {
|
|
341
343
|
return { running: false, reason: 'nothing is listening; start any AI client, or run a command and it will start itself' };
|
|
@@ -361,6 +363,21 @@ export function statusLines(s) {
|
|
|
361
363
|
`paired: ${s.paired ? 'yes' : 'no (enter the 6-digit code in the extension, see `replywizard pair`)'}`,
|
|
362
364
|
`sessions: ${s.sessions}`,
|
|
363
365
|
`token: ${s.tokenPresent ? 'present' : 'missing (~/.replywizard-mcp/daemon-token.json)'}`,
|
|
366
|
+
/*
|
|
367
|
+
* WHICH directory, always, and not only when something is wrong.
|
|
368
|
+
*
|
|
369
|
+
* The daemon is spawned by whichever AI client started first, with that client's
|
|
370
|
+
* environment, so an editor that runs sandboxed (flatpak, snap) gives its daemon a
|
|
371
|
+
* different HOME and therefore a different session file: it knows nothing of the pairing
|
|
372
|
+
* every other client shares, and asks for a six-digit code that the other daemon then
|
|
373
|
+
* does not recognise either. Printed here, the two daemons tell themselves apart at a
|
|
374
|
+
* glance; before this there was nothing to compare.
|
|
375
|
+
*/
|
|
376
|
+
`state: ${s.stateDir || 'unknown (this host is older than 0.3.2)'}`,
|
|
377
|
+
...(s.persistError
|
|
378
|
+
? [`WARNING: this daemon cannot save its state: ${s.persistError}`,
|
|
379
|
+
' Pairing will work until the daemon restarts, and then be asked for again.']
|
|
380
|
+
: []),
|
|
364
381
|
];
|
|
365
382
|
}
|
|
366
383
|
|
package/src/connector.js
CHANGED
|
@@ -24,16 +24,88 @@ const HOST = '127.0.0.1';
|
|
|
24
24
|
const log = (...args) => console.error('[replywizard-mcp:connector]', ...args);
|
|
25
25
|
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* JSON-RPC error handed back when a request cannot reach the daemon, or when the daemon goes
|
|
29
|
+
* away while the request is in flight. -32000 is the "implementation-defined server error"
|
|
30
|
+
* range, which is what this is: the protocol was fine and the hop underneath it was not.
|
|
31
|
+
*/
|
|
32
|
+
const DAEMON_GONE = -32000;
|
|
33
|
+
const DAEMON_GONE_TEXT =
|
|
34
|
+
'The Reply Wizard MCP daemon is not reachable. It may have been stopped, or the machine '
|
|
35
|
+
+ 'may have slept. Run `replywizard status` to restart it, then try again.';
|
|
36
|
+
|
|
37
|
+
/** A JSON-RPC REQUEST is the only frame anybody is waiting on: it has BOTH an id and a method. */
|
|
38
|
+
function isRequest(msg) {
|
|
39
|
+
return !!msg && typeof msg === 'object' && msg.method !== undefined
|
|
40
|
+
&& msg.id !== undefined && msg.id !== null;
|
|
41
|
+
}
|
|
42
|
+
|
|
27
43
|
/**
|
|
28
44
|
* Wire two MCP transports so every message on one is forwarded to the other, in both
|
|
29
45
|
* directions, and a close/error on either tears down the pair. Pure plumbing: no
|
|
30
|
-
* protocol knowledge
|
|
46
|
+
* protocol knowledge beyond "which frames is somebody waiting for an answer to".
|
|
47
|
+
*
|
|
48
|
+
* WHY THIS IS NOT A BARE RELAY, AND THE MEASUREMENT BEHIND IT (2026-09-21)
|
|
49
|
+
* It used to be one: a failed forward was `.catch((e) => log(...))`, logged to stderr and
|
|
50
|
+
* swallowed. **stderr is not shown to anyone.** An MCP client that had sent `tools/call` and
|
|
51
|
+
* whose request could not be forwarded therefore waited FOR EVER, because a JSON-RPC client
|
|
52
|
+
* has nothing to wait on but the matching id.
|
|
53
|
+
*
|
|
54
|
+
* That is not theoretical. The owner hit it on 2026-09-21 and reported it as "you were
|
|
55
|
+
* working for an unusually long time on a single tool call", and the only way out was to
|
|
56
|
+
* interrupt. Reproduced deterministically: connect a client, prove a call works, `kill -9`
|
|
57
|
+
* the daemon, send the same call again -- the connector printed `→daemon send failed: fetch
|
|
58
|
+
* failed` and the client received nothing in 30 seconds and would have received nothing ever.
|
|
59
|
+
*
|
|
60
|
+
* A daemon that dies is ordinary. It is a detached background process, so it goes with a
|
|
61
|
+
* crash, a laptop sleeping, an OOM kill, `pkill node`, or a machine restart, and the client
|
|
62
|
+
* that started it has no idea. **The failure is unavoidable; being silent about it is not.**
|
|
63
|
+
*
|
|
64
|
+
* So every frame anybody is waiting on gets an answer, one way or the other:
|
|
65
|
+
* - a request that cannot be FORWARDED is answered immediately with an error, and
|
|
66
|
+
* - a request already IN FLIGHT when the daemon drops is answered on the way down,
|
|
67
|
+
* which is why `pending` exists rather than only a catch.
|
|
68
|
+
* Notifications and responses are still relayed best-effort and still only logged: nothing
|
|
69
|
+
* is waiting on them, and inventing an error for a notification would corrupt the stream.
|
|
31
70
|
*/
|
|
32
71
|
export function pumpTransports(clientFacing, daemonFacing) {
|
|
33
|
-
|
|
34
|
-
|
|
72
|
+
/** Request ids the client is waiting on. Settled by the daemon, or by us on the way down. */
|
|
73
|
+
const pending = new Set();
|
|
74
|
+
|
|
75
|
+
const failClient = (id, message) => {
|
|
76
|
+
pending.delete(id);
|
|
77
|
+
clientFacing.send({ jsonrpc: '2.0', id, error: { code: DAEMON_GONE, message } })
|
|
78
|
+
.catch((e) => log('could not report the failure to the client:', e && e.message));
|
|
79
|
+
};
|
|
80
|
+
/** Answer everything still outstanding. Called once, when the daemon side goes away. */
|
|
81
|
+
const failAllPending = () => {
|
|
82
|
+
if (!pending.size) return;
|
|
83
|
+
log(`daemon gone with ${pending.size} request(s) in flight; answering them with an error.`);
|
|
84
|
+
for (const id of [...pending]) failClient(id, DAEMON_GONE_TEXT);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
clientFacing.onmessage = (msg) => {
|
|
88
|
+
const waiting = isRequest(msg);
|
|
89
|
+
if (waiting) pending.add(msg.id);
|
|
90
|
+
daemonFacing.send(msg).catch((e) => {
|
|
91
|
+
log('→daemon send failed:', e && e.message);
|
|
92
|
+
// The whole point: a request that never reached the daemon is answered here, because
|
|
93
|
+
// nothing downstream exists to answer it.
|
|
94
|
+
if (waiting) failClient(msg.id, DAEMON_GONE_TEXT);
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
daemonFacing.onmessage = (msg) => {
|
|
98
|
+
// Any frame carrying an id settles that id, whether it is a result or an error.
|
|
99
|
+
if (msg && typeof msg === 'object' && msg.id !== undefined && msg.id !== null) pending.delete(msg.id);
|
|
100
|
+
clientFacing.send(msg).catch((e) => log('→client send failed:', e && e.message));
|
|
101
|
+
};
|
|
35
102
|
clientFacing.onclose = () => { daemonFacing.close().catch(() => {}); };
|
|
36
|
-
daemonFacing.onclose = () => {
|
|
103
|
+
daemonFacing.onclose = () => {
|
|
104
|
+
// Before the client transport goes, not after: once it is closed nothing can be sent on
|
|
105
|
+
// it, and the in-flight requests would be lost in exactly the silent way this fixes.
|
|
106
|
+
failAllPending();
|
|
107
|
+
clientFacing.close().catch(() => {});
|
|
108
|
+
};
|
|
37
109
|
clientFacing.onerror = (e) => log('client transport error:', e && e.message);
|
|
38
110
|
daemonFacing.onerror = (e) => log('daemon transport error:', e && e.message);
|
|
39
111
|
}
|
package/src/daemon.js
CHANGED
|
@@ -20,14 +20,14 @@
|
|
|
20
20
|
|
|
21
21
|
import http from 'node:http';
|
|
22
22
|
import { randomUUID } from 'node:crypto';
|
|
23
|
-
import {
|
|
23
|
+
import { realpathSync } from 'node:fs';
|
|
24
24
|
import { fileURLToPath } from 'node:url';
|
|
25
25
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
26
26
|
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
27
|
-
import { ExtensionBridge } from './wsServer.js';
|
|
27
|
+
import { ExtensionBridge, stateDir as stateDirPath } from './wsServer.js';
|
|
28
28
|
import { createMcpServer } from './mcpServer.js';
|
|
29
29
|
import { DEFAULT_PORT } from './protocol.js';
|
|
30
|
-
import { loadOrCreateToken, tokenMatches, bearerFrom } from './daemonAuth.js';
|
|
30
|
+
import { loadOrCreateToken, tokenMatches, bearerFrom, tokenWriteError } from './daemonAuth.js';
|
|
31
31
|
import { hostVersion } from './hostVersion.js';
|
|
32
32
|
|
|
33
33
|
// Daemon-only (not part of the extension wire contract, so it lives here rather than
|
|
@@ -173,6 +173,13 @@ export function createDaemon({
|
|
|
173
173
|
extensionConnected: connected,
|
|
174
174
|
paired: !!(bridge && bridge.paired),
|
|
175
175
|
sessions: sessions.size,
|
|
176
|
+
// WHERE state is kept, and WHETHER it could be written. Two different ways a customer
|
|
177
|
+
// ends up typing a pairing code again and again, and from the outside they look the
|
|
178
|
+
// same: a daemon started from a sandboxed editor resolves a different HOME and reads
|
|
179
|
+
// a different session file, and a daemon whose $HOME is unwritable cannot keep the
|
|
180
|
+
// pairing it just made. Neither was visible from anywhere before 0.3.2.
|
|
181
|
+
stateDir: stateDirPath(),
|
|
182
|
+
persistError: (bridge && bridge.persistError) || tokenWriteError() || null,
|
|
176
183
|
});
|
|
177
184
|
return;
|
|
178
185
|
}
|
package/src/daemonAuth.js
CHANGED
|
@@ -12,15 +12,18 @@
|
|
|
12
12
|
// the real ~/.replywizard-mcp).
|
|
13
13
|
|
|
14
14
|
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
15
|
-
import { homedir } from 'node:os';
|
|
16
15
|
import { join } from 'node:path';
|
|
17
|
-
import {
|
|
16
|
+
import { readJson, stateDir, writeJsonVerified } from './stateStore.js';
|
|
18
17
|
|
|
19
18
|
const log = (...args) => console.error('[replywizard-mcp]', ...args);
|
|
20
19
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
// The last persistence failure, or null. `loadOrCreateToken` hands a working token back
|
|
21
|
+
// either way -- the daemon runs, and clients that read the token from THIS process work --
|
|
22
|
+
// but the next daemon mints a different one and every configured client is refused, which is
|
|
23
|
+
// why the daemon reports this on /healthz rather than leaving it in a log nobody sees.
|
|
24
|
+
let lastWriteError = null;
|
|
25
|
+
export function tokenWriteError() { return lastWriteError; }
|
|
26
|
+
|
|
24
27
|
function tokenFile(dir) {
|
|
25
28
|
return join(stateDir(dir), 'daemon-token.json');
|
|
26
29
|
}
|
|
@@ -34,18 +37,17 @@ function tokenFile(dir) {
|
|
|
34
37
|
// (`rotateToken`), which is what keeps the difference tolerable rather than a hole.
|
|
35
38
|
// Surfaced by the cross-platform CI matrix, 2026-08-20.
|
|
36
39
|
function writeToken(token, dir) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
40
|
+
// Atomic (temp file then rename) and READ BACK, via stateStore.js: a write that failed used
|
|
41
|
+
// to be a line on a stderr the daemon does not have, and a write that half-landed read back
|
|
42
|
+
// as "no token at all", which is the same thing to every caller here.
|
|
43
|
+
lastWriteError = writeJsonVerified(tokenFile(dir), { token }, (back) => back && back.token === token);
|
|
44
|
+
if (lastWriteError) log('Could not persist daemon auth token:', lastWriteError);
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
/** Read the persisted token, or null if none / unreadable. */
|
|
46
48
|
export function readToken(dir) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
const raw = readJson(tokenFile(dir));
|
|
50
|
+
return (raw && raw.token) || null;
|
|
49
51
|
}
|
|
50
52
|
|
|
51
53
|
/** Return the persisted token, creating + persisting a fresh one if absent. */
|
package/src/protocol.js
CHANGED
|
@@ -36,8 +36,32 @@ export const STATUS = Object.freeze({
|
|
|
36
36
|
CONNECTING: 'connecting',
|
|
37
37
|
AUTH_REQUIRED: 'auth_required',
|
|
38
38
|
CONNECTED: 'connected',
|
|
39
|
+
// Another browser holds the one extension socket. See CLOSE_BUSY.
|
|
40
|
+
BUSY: 'busy',
|
|
39
41
|
});
|
|
40
42
|
|
|
43
|
+
/*
|
|
44
|
+
* The hub's refusal code, and the single most confusing state this subsystem has.
|
|
45
|
+
*
|
|
46
|
+
* `wsServer._onConnection` accepts ONE extension socket and closes any other with
|
|
47
|
+
* `1013` and the reason `busy`. That is correct and deliberate: the singleton is the
|
|
48
|
+
* BROWSER, because two browsers are two different WhatsApp accounts as far as an
|
|
49
|
+
* assistant is concerned, and silently swapping which one answers is a data problem
|
|
50
|
+
* rather than a cosmetic one.
|
|
51
|
+
*
|
|
52
|
+
* What was missing is that nobody read the code. `mcpBridge.js`'s `onclose` ignored it,
|
|
53
|
+
* so a second browser reported plain `disconnected` and retried on the fast backoff.
|
|
54
|
+
* Diagnosed live 2026-09-10 on a machine running two Chrome profiles: the two took
|
|
55
|
+
* turns holding the socket, each presented its own session token, each mismatched the
|
|
56
|
+
* other's, and every reconnect minted a fresh pairing code. `session.json` was rewritten
|
|
57
|
+
* three times in nine minutes -- and it is only written on a SUCCESSFUL pairing -- with
|
|
58
|
+
* `/healthz` reporting `paired: false` in between. It reads as "pairing is broken" when
|
|
59
|
+
* the truth is "you have two browsers and only one can have it".
|
|
60
|
+
*
|
|
61
|
+
* 1013 is `Try Again Later` in RFC 6455, which is exactly the situation.
|
|
62
|
+
*/
|
|
63
|
+
export const CLOSE_BUSY = 1013;
|
|
64
|
+
|
|
41
65
|
export const CONTROL = Object.freeze({
|
|
42
66
|
HANDSHAKE: 'handshake',
|
|
43
67
|
PAIRING_REQUEST: 'pairing_request',
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// stateStore.js: where this package keeps state, and the only way it writes it.
|
|
2
|
+
//
|
|
3
|
+
// Two files live in `~/.replywizard-mcp` and both are load-bearing: `session.json` holds the
|
|
4
|
+
// tokens that keep a paired browser paired, and `daemon-token.json` holds the bearer token
|
|
5
|
+
// every AI client must present. Until 2026-09-17 each was written with a bare `writeFileSync`
|
|
6
|
+
// inside a `try` whose `catch` called `log()`, and `log()` writes to stderr, which is
|
|
7
|
+
// `/dev/null` for the daemon the connector spawns (`stdio: 'ignore'`). So a write that failed
|
|
8
|
+
// -- an unwritable or full `$HOME`, a container mount, a profile on a read-only volume --
|
|
9
|
+
// produced a pairing that worked until the daemon restarted and then never again, with
|
|
10
|
+
// nothing said anywhere. Worse, `writeFileSync` is not atomic: a crash or a full disk
|
|
11
|
+
// mid-write leaves a truncated file, and the reader's `catch` turns that into "no token",
|
|
12
|
+
// which is indistinguishable from "never paired".
|
|
13
|
+
//
|
|
14
|
+
// So every write here is write-temp-then-rename (atomic within a directory) and is READ BACK
|
|
15
|
+
// before it is called a success. The caller gets a reason string rather than an exception,
|
|
16
|
+
// because none of these callers can do anything about the failure except REPORT it, and
|
|
17
|
+
// reporting it is the whole point: `wsServer.js` puts it on the wire so the extension can say
|
|
18
|
+
// so, and the daemon puts it in `/healthz` so `replywizard status` can print it.
|
|
19
|
+
|
|
20
|
+
import { homedir } from 'node:os';
|
|
21
|
+
import { dirname, join } from 'node:path';
|
|
22
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The state directory. Overridable via `RW_MCP_STATE_DIR`, which is how the test suite keeps
|
|
26
|
+
* off the real one, and resolved on every call so the environment can change after import.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} [dir] an explicit directory, which wins over everything (daemonAuth's API)
|
|
29
|
+
*/
|
|
30
|
+
export function stateDir(dir) {
|
|
31
|
+
return dir || process.env.RW_MCP_STATE_DIR || join(homedir(), '.replywizard-mcp');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Parse a JSON file, or null if it is missing, unreadable or not JSON. */
|
|
35
|
+
export function readJson(file) {
|
|
36
|
+
try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Write JSON atomically and prove it landed.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} file
|
|
43
|
+
* @param {object} obj
|
|
44
|
+
* @param {(back: any) => boolean} [verify] what "it landed" means for this caller, given the
|
|
45
|
+
* re-read object. Defaults to a deep-enough comparison of the serialized form.
|
|
46
|
+
* @returns {string|null} null on success, else a reason short enough to put on a wire
|
|
47
|
+
*/
|
|
48
|
+
export function writeJsonVerified(file, obj, verify) {
|
|
49
|
+
const body = JSON.stringify(obj);
|
|
50
|
+
const tmp = `${file}.tmp`;
|
|
51
|
+
try {
|
|
52
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
53
|
+
// The temp file is a SIBLING, not in the system temp dir: rename is only atomic within one
|
|
54
|
+
// filesystem, and `$HOME` and `/tmp` are routinely two.
|
|
55
|
+
writeFileSync(tmp, body, { mode: 0o600 });
|
|
56
|
+
renameSync(tmp, file);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
try { rmSync(tmp, { force: true }); } catch { /* the write is already the failure */ }
|
|
59
|
+
return (e && e.message) || 'write failed';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const back = readJson(file);
|
|
63
|
+
if (back === null) return 'written, but the file could not be read back';
|
|
64
|
+
const ok = verify ? verify(back) : JSON.stringify(back) === body;
|
|
65
|
+
return ok ? null : 'written, but the file does not hold what was just written';
|
|
66
|
+
}
|
package/src/tools.js
CHANGED
|
@@ -22,7 +22,9 @@ export const TOOLS = [
|
|
|
22
22
|
name: ACTIONS.LIST_CHATS,
|
|
23
23
|
description:
|
|
24
24
|
'List the user\'s WhatsApp chats, most recently active first. Returns id, name, ' +
|
|
25
|
-
'isGroup, unreadCount and timestamp for each. Use the returned `id` with
|
|
25
|
+
'phone, isGroup, unreadCount and timestamp for each. Use the returned `id` with ' +
|
|
26
|
+
'get_messages. `phone` is the dialable number in digits, or null: a group never has ' +
|
|
27
|
+
'one, and a small number of one-to-one chats do not either, so it is never required.',
|
|
26
28
|
inputSchema: {
|
|
27
29
|
type: 'object',
|
|
28
30
|
properties: {
|
package/src/wsServer.js
CHANGED
|
@@ -23,27 +23,65 @@
|
|
|
23
23
|
|
|
24
24
|
import { WebSocketServer } from 'ws';
|
|
25
25
|
import { randomBytes, randomUUID } from 'node:crypto';
|
|
26
|
-
import {
|
|
26
|
+
import { platform } from 'node:os';
|
|
27
27
|
import { join } from 'node:path';
|
|
28
|
-
import { mkdirSync,
|
|
28
|
+
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
|
29
29
|
import { spawn } from 'node:child_process';
|
|
30
30
|
import { CONTROL, DEFAULT_PORT, PROTOCOL_VERSION, VALUE_ACTIONS } from './protocol.js';
|
|
31
31
|
import { hostVersion } from './hostVersion.js';
|
|
32
|
+
import { readJson, stateDir, writeJsonVerified } from './stateStore.js';
|
|
32
33
|
|
|
33
34
|
const log = (...args) => console.error('[replywizard-mcp]', ...args);
|
|
34
35
|
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
// a
|
|
38
|
-
|
|
36
|
+
// The state dir is `stateStore.js`'s (overridable via RW_MCP_STATE_DIR, resolved on every call
|
|
37
|
+
// so the environment can change after import). Exported because the daemon reports it on
|
|
38
|
+
// /healthz and `replywizard status` prints it: a client whose editor runs sandboxed resolves a
|
|
39
|
+
// different HOME, so its daemon reads a different session file and asks to pair again, and
|
|
40
|
+
// until this was printed that was indistinguishable from a failed write.
|
|
41
|
+
export { stateDir };
|
|
39
42
|
function stateFile() { return join(stateDir(), 'session.json'); }
|
|
40
43
|
|
|
41
|
-
|
|
42
|
-
|
|
44
|
+
/**
|
|
45
|
+
* HOW MANY BROWSERS MAY STAY PAIRED AT ONCE.
|
|
46
|
+
*
|
|
47
|
+
* The file held ONE token until 2026-09-17, and `_onConnection` refuses a second extension
|
|
48
|
+
* socket, so a user with two Chrome profiles (or Chrome and Edge) had each pairing invalidate
|
|
49
|
+
* the other's: whichever browser took the socket next was asked for a fresh six-digit code,
|
|
50
|
+
* for ever, and neither was doing anything wrong. A small SET fixes that without weakening
|
|
51
|
+
* anything -- each token is still 256 bits, still minted only by a completed pairing, and
|
|
52
|
+
* still only ever compared -- and a cap keeps the file from becoming a list of every browser
|
|
53
|
+
* that ever touched this machine. Five is the number of profiles a person plausibly runs; the
|
|
54
|
+
* least recently used is dropped, so the browsers actually in use are the ones that survive.
|
|
55
|
+
*/
|
|
56
|
+
const MAX_SESSION_TOKENS = 5;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Read the persisted tokens, newest first.
|
|
60
|
+
*
|
|
61
|
+
* Accepts the pre-2026-09-17 `{ "token": "..." }` shape as well, because an upgrade must not
|
|
62
|
+
* unpair the browser it finds already paired -- which is the exact failure this whole change
|
|
63
|
+
* is about.
|
|
64
|
+
*/
|
|
65
|
+
function loadTokens() {
|
|
66
|
+
const raw = readJson(stateFile());
|
|
67
|
+
const list = Array.isArray(raw && raw.tokens) ? raw.tokens : (raw && typeof raw.token === 'string' ? [raw.token] : []);
|
|
68
|
+
return list.filter((t) => typeof t === 'string' && t).slice(0, MAX_SESSION_TOKENS);
|
|
43
69
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Persist the tokens, atomically, and prove it landed. Returns null, or a reason to report.
|
|
73
|
+
*
|
|
74
|
+
* `token` is written beside `tokens` on purpose: an OLDER host reading this file still finds
|
|
75
|
+
* the newest token where it expects one, so downgrading the package does not unpair anybody.
|
|
76
|
+
*/
|
|
77
|
+
function saveTokens(tokens) {
|
|
78
|
+
const reason = writeJsonVerified(
|
|
79
|
+
stateFile(),
|
|
80
|
+
{ version: 2, tokens, token: tokens[0] || null },
|
|
81
|
+
(back) => Array.isArray(back.tokens) && back.tokens.length === tokens.length && back.tokens[0] === tokens[0],
|
|
82
|
+
);
|
|
83
|
+
if (reason) log('Could not persist the session token:', reason);
|
|
84
|
+
return reason;
|
|
47
85
|
}
|
|
48
86
|
|
|
49
87
|
// When the daemon runs detached (spawned by the connector, stderr → /dev/null), the
|
|
@@ -170,7 +208,10 @@ export class ExtensionBridge {
|
|
|
170
208
|
this._pairingTimer = null; // TTL timer that expires the current code
|
|
171
209
|
this.maxPairingAttempts = opts.maxPairingAttempts ?? MAX_PAIRING_ATTEMPTS;
|
|
172
210
|
this.pairingCodeTtlMs = opts.pairingCodeTtlMs ?? PAIRING_CODE_TTL_MS;
|
|
173
|
-
this.
|
|
211
|
+
this.sessionTokens = loadTokens(); // newest first; `sessionToken` below is the head
|
|
212
|
+
// The last persistence failure, or null. Reported on the wire and on /healthz rather than
|
|
213
|
+
// only logged, because the log goes nowhere for a daemon the connector spawned detached.
|
|
214
|
+
this.persistError = null;
|
|
174
215
|
this.pending = new Map(); // requestId → { entry, lane }
|
|
175
216
|
this.requestTimeoutMs = opts.requestTimeoutMs ?? 25_000;
|
|
176
217
|
this.listening = false;
|
|
@@ -272,6 +313,32 @@ export class ExtensionBridge {
|
|
|
272
313
|
this._pairingTimer = null;
|
|
273
314
|
}
|
|
274
315
|
|
|
316
|
+
/**
|
|
317
|
+
* The newest token, which is what a single-token caller means by "the" session token.
|
|
318
|
+
* Kept as an accessor so `bridge.sessionToken = x` still means what it always did, in the
|
|
319
|
+
* daemon, in the tests, and in any client of this class.
|
|
320
|
+
*/
|
|
321
|
+
get sessionToken() { return this.sessionTokens[0] || null; }
|
|
322
|
+
set sessionToken(token) { this.sessionTokens = token ? [token] : []; }
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Is this one of the tokens we issued? If so, move it to the head.
|
|
326
|
+
*
|
|
327
|
+
* The promotion is what makes the cap safe: with two browsers taking turns, the one that
|
|
328
|
+
* has not connected for longest is the one dropped when a sixth pairing arrives, rather
|
|
329
|
+
* than whichever happens to sit at the end of the array. It writes only when the order
|
|
330
|
+
* actually changes, so an ordinary reconnect (already the head) costs no disk at all.
|
|
331
|
+
*/
|
|
332
|
+
_acceptToken(token) {
|
|
333
|
+
const at = this.sessionTokens.indexOf(token);
|
|
334
|
+
if (at === -1) return false;
|
|
335
|
+
if (at > 0) {
|
|
336
|
+
this.sessionTokens = [token, ...this.sessionTokens.filter((t) => t !== token)];
|
|
337
|
+
this.persistError = saveTokens(this.sessionTokens);
|
|
338
|
+
}
|
|
339
|
+
return true;
|
|
340
|
+
}
|
|
341
|
+
|
|
275
342
|
_onConnection(ws) {
|
|
276
343
|
if (this.socket && this.socket.readyState === this.socket.OPEN) {
|
|
277
344
|
log('Rejecting extra connection; one extension is already connected.');
|
|
@@ -318,9 +385,9 @@ export class ExtensionBridge {
|
|
|
318
385
|
|
|
319
386
|
if (msg.method === CONTROL.HANDSHAKE) {
|
|
320
387
|
const token = msg.params && msg.params.session_token;
|
|
321
|
-
if (token && this.
|
|
388
|
+
if (token && this._acceptToken(token)) {
|
|
322
389
|
this.paired = true;
|
|
323
|
-
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion() } });
|
|
390
|
+
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion(), session_persisted: !this.persistError } });
|
|
324
391
|
this._sendClients(); // sync current assistants to a freshly reconnected extension
|
|
325
392
|
log('Reconnected with a valid session token (no pairing needed).');
|
|
326
393
|
} else if (this._pairingCodeIsLive()) {
|
|
@@ -360,13 +427,17 @@ export class ExtensionBridge {
|
|
|
360
427
|
this.paired = true;
|
|
361
428
|
// 256-bit token (hex): matches the daemon's HTTP token strength, rather
|
|
362
429
|
// than randomUUID's ~122 bits of entropy (L1).
|
|
363
|
-
|
|
364
|
-
|
|
430
|
+
const token = randomBytes(32).toString('hex');
|
|
431
|
+
this.sessionTokens = [token, ...this.sessionTokens.filter((t) => t !== token)].slice(0, MAX_SESSION_TOKENS);
|
|
432
|
+
this.persistError = saveTokens(this.sessionTokens);
|
|
365
433
|
clearPairingCode();
|
|
366
434
|
this._resetPairing();
|
|
367
|
-
|
|
435
|
+
// `session_persisted: false` says "you are paired now, and this will not survive a
|
|
436
|
+
// restart". The extension shows it; without it the only trace is a log nobody reads
|
|
437
|
+
// and a code that comes back tomorrow for no visible reason.
|
|
438
|
+
this._send({ method: CONTROL.PAIRING_COMPLETE, params: { session_id: randomUUID(), session_token: token, session_persisted: !this.persistError } });
|
|
368
439
|
// Row 48: the extension cannot otherwise tell a current bridge from a stale one.
|
|
369
|
-
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion() } });
|
|
440
|
+
this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion(), session_persisted: !this.persistError } });
|
|
370
441
|
this._sendClients(); // sync current assistants right after pairing
|
|
371
442
|
log('Pairing approved.');
|
|
372
443
|
} else {
|