replywizard-whatsapp-mcp 0.6.4 → 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 CHANGED
@@ -148,6 +148,10 @@ the entry in the editor's own MCP panel as well.
148
148
 
149
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.
150
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
+
151
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.
152
156
 
153
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`.
@@ -299,7 +303,7 @@ claude mcp add rw --transport http http://127.0.0.1:7870/mcp --header "Authoriza
299
303
  ### Auth token
300
304
 
301
305
  The daemon generates a bearer token on first start at `~/.replywizard-mcp/daemon-token.json` (mode
302
- `600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz` is open.
306
+ `600`). Every `/mcp` request must present it (`Authorization: Bearer <token>`); `/healthz` needs no token but, from 0.6.4, a loopback `Host` header.
303
307
  The connector reads it automatically. **To revoke**, delete that file (the daemon mints a new one on
304
308
  next start): existing clients must pick up the new token.
305
309
 
@@ -357,6 +361,8 @@ client. Printed, the two tell themselves apart.
357
361
 
358
362
  - Binds to `127.0.0.1` only.
359
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.
360
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
361
367
  `send_message` call is sent only when you press Send in WhatsApp Web; no tool edits or deletes a
362
368
  message.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.6.4",
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": {
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
- export const PROTOCOL_VERSION = 1;
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/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 `handshake { session_token }` on connect.
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.
@@ -373,9 +419,11 @@ export class ExtensionBridge {
373
419
  * actually changes, so an ordinary reconnect (already the head) costs no disk at all.
374
420
  */
375
421
  _acceptToken(token) {
376
- const at = this.sessionTokens.indexOf(token);
422
+ let at = -1;
423
+ this.sessionTokens.forEach((t, i) => { if (safeEqual(t, token) && at === -1) at = i; });
377
424
  if (at === -1) return false;
378
425
  if (at > 0) {
426
+ token = this.sessionTokens[at];
379
427
  this.sessionTokens = [token, ...this.sessionTokens.filter((t) => t !== token)];
380
428
  this.persistError = saveTokens(this.sessionTokens);
381
429
  }
@@ -390,6 +438,7 @@ export class ExtensionBridge {
390
438
  }
391
439
  this.socket = ws;
392
440
  this.paired = false;
441
+ this._challenge = null; // a challenge belongs to the socket it was issued on
393
442
  // A LIVE pairing code survives the reconnect, deliberately.
394
443
  //
395
444
  // It used to be thrown away here and a new one minted on the next handshake, which
@@ -414,6 +463,7 @@ export class ExtensionBridge {
414
463
  if (this.socket === ws) {
415
464
  this.socket = null;
416
465
  this.paired = false;
466
+ this._challenge = null;
417
467
  // Same rule as `_onConnection`: a code the user may still be typing outlives the
418
468
  // socket it was minted for. An expired one is cleared here so nothing lingers.
419
469
  if (!this._pairingCodeIsLive()) this._resetPairing();
@@ -426,52 +476,24 @@ export class ExtensionBridge {
426
476
  let msg;
427
477
  try { msg = JSON.parse(raw.toString()); } catch { log('Dropped non-JSON message'); return; }
428
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
+
429
482
  if (msg.method === CONTROL.HANDSHAKE) {
430
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
+ }
431
491
  if (token && this._acceptToken(token)) {
432
492
  this.paired = true;
433
- this._send({ method: CONTROL.AUTH_SUCCESS, params: { protocol: PROTOCOL_VERSION, host_version: hostVersion(), session_persisted: !this.persistError } });
434
- this._sendClients(); // sync current assistants to a freshly reconnected extension
435
- log('Reconnected with a valid session token (no pairing needed).');
436
- } else if (this._pairingCodeIsLive()) {
437
- // The code from before the reconnect is still good. Say so in the log and do NOT
438
- // toast again: one code, one notification. The file is rewritten because it is a
439
- // mirror rather than the source of truth, so this heals a deleted one.
440
- writePairingCode(this.pairingCode);
441
- const secondsLeft = Math.max(1, Math.round((this.pairingCodeExpiresAt - Date.now()) / 1000));
442
- log(`Reconnected while unpaired; the existing code is still valid for ~${secondsLeft}s `
443
- + `(${this.pairingAttempts}/${this.maxPairingAttempts} wrong attempts used).`);
444
- 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).');
445
495
  } else {
446
- const now = Date.now();
447
- this._codeMints = this._codeMints.filter((t) => now - t < this.pairingCodeWindowMs);
448
- if (this._codeMints.length >= this.pairingCodesPerWindow) {
449
- // The socket stays open on purpose: closing it makes the extension reconnect and ask
450
- // again on its backoff, which clears the error it would otherwise show.
451
- const retryAfterS = Math.max(1, Math.ceil((this._codeMints[0] + this.pairingCodeWindowMs - now) / 1000));
452
- this._send({ method: CONTROL.PAIRING_FAILED, params: { reason: 'rate_limited', retry_after_s: retryAfterS } });
453
- log(`Pairing refused: ${this.pairingCodesPerWindow} codes were issued in the last `
454
- + `${Math.round(this.pairingCodeWindowMs / 60_000)} minutes. Try again in ~${retryAfterS}s.`);
455
- return;
456
- }
457
- // A code that replaces one locked out by wrong guesses is not announced unless it is
458
- // the first of the window: that is the brute-force path, and each toast was a process
459
- // launch on the desktop. A code that replaces an EXPIRED one is announced, because a
460
- // person who came back after five minutes needs to see it, and expiry cannot be sped up.
461
- const announce = this._codeMints.length === 0 || !this._lastCodeLockedOut;
462
- this._codeMints.push(now);
463
- this._lastCodeLockedOut = false;
464
- this._setPairingCode(sixDigitCode());
465
- writePairingCode(this.pairingCode);
466
- if (announce) { try { this._notify(this.pairingCode); } catch { /* notifier is best-effort */ } }
467
- log('');
468
- log(' ┌──────────────────────────────────────────────┐');
469
- log(` │ Reply Wizard pairing code: ${this.pairingCode} │`);
470
- log(' └──────────────────────────────────────────────┘');
471
- log(' Enter it in Reply Wizard → Settings → WhatsApp MCP.');
472
- log(' (A desktop notification with the code should also appear.)');
473
- log(` (Running in the background? Read it from ${pairingFile()})`);
474
- this._send({ method: CONTROL.PAIRING_REQUEST, params: { hub_name: 'Reply Wizard MCP', protocol: PROTOCOL_VERSION } });
496
+ this._startPairing();
475
497
  }
476
498
  return;
477
499
  }
@@ -538,6 +560,106 @@ export class ExtensionBridge {
538
560
  }
539
561
  }
540
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
+
541
663
  /**
542
664
  * Forward an action to the extension and await the result. Scheduled in a lane
543
665
  * (read vs value) with bounded concurrency + per-lane backpressure; the per-action