@wonderwhy-er/desktop-commander 0.2.46 → 0.2.47

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
@@ -88,11 +88,10 @@ Execute long-running terminal commands on your computer and manage processes thr
88
88
  - All tool calls are automatically logged
89
89
  - Log rotation with 10MB size limit
90
90
  - Detailed timestamps and arguments
91
- - Security hardening:
91
+ - Safety guardrails (not a sandbox — see [SECURITY.md](SECURITY.md)):
92
92
  - Symlink traversal prevention on file operations
93
- - Command blocklist with bypass protection
94
- - [Docker isolation](#option-6-docker-installation--auto-updates-no-nodejs-required) for full sandboxing
95
- - See [SECURITY.md](SECURITY.md) for details
93
+ - Command blocklist for accidental execution
94
+ - [Docker isolation](#option-6-docker-installation--auto-updates-no-nodejs-required) for complete isolation
96
95
 
97
96
  ## How to install
98
97
 
@@ -10,6 +10,8 @@ export declare class MCPDevice {
10
10
  private configPath;
11
11
  private persistSession;
12
12
  private desktop;
13
+ /** Call ids already handled by THIS process (insertion-ordered, bounded). */
14
+ private seenCallIds;
13
15
  constructor(options?: MCPDeviceOptions);
14
16
  private setupShutdownHandlers;
15
17
  start(): Promise<void>;
@@ -19,6 +21,8 @@ export declare class MCPDevice {
19
21
  supabaseUrl: any;
20
22
  anonKey: any;
21
23
  }>;
24
+ /** Record a handled call id, evicting the oldest once the cap is reached. */
25
+ private rememberCallId;
22
26
  handleNewToolCall(payload: any): Promise<void>;
23
27
  shutdown(): Promise<void>;
24
28
  }
@@ -7,8 +7,18 @@ import os from 'os';
7
7
  import fs from 'fs/promises';
8
8
  import path from 'path';
9
9
  import { captureRemote } from '../utils/capture.js';
10
+ /**
11
+ * How many recently-handled call ids to remember for duplicate-delivery
12
+ * suppression. The two transports deliver a call within MILLISECONDS of each
13
+ * other, so this only has to outlive that window — 100 ids is several minutes
14
+ * of even the heaviest agent traffic, and costs ~10 KB on the user's machine
15
+ * (the device process, not the shared server).
16
+ */
17
+ const SEEN_CALL_IDS_MAX = 100;
10
18
  export class MCPDevice {
11
19
  constructor(options = {}) {
20
+ /** Call ids already handled by THIS process (insertion-ordered, bounded). */
21
+ this.seenCallIds = new Set();
12
22
  this.baseServerUrl = process.env.MCP_SERVER_URL || 'https://mcp.desktopcommander.app';
13
23
  this.remoteChannel = new RemoteChannel();
14
24
  this.deviceId = undefined;
@@ -212,6 +222,16 @@ export class MCPDevice {
212
222
  };
213
223
  }
214
224
  // Methods moved to RemoteChannel
225
+ /** Record a handled call id, evicting the oldest once the cap is reached. */
226
+ rememberCallId(callId) {
227
+ this.seenCallIds.add(callId);
228
+ if (this.seenCallIds.size > SEEN_CALL_IDS_MAX) {
229
+ // Sets iterate in insertion order — drop the oldest entry.
230
+ const oldest = this.seenCallIds.values().next().value;
231
+ if (oldest !== undefined)
232
+ this.seenCallIds.delete(oldest);
233
+ }
234
+ }
215
235
  async handleNewToolCall(payload) {
216
236
  const toolCall = payload.new;
217
237
  // Expect toolCall to include a device_id field used to route calls to this device instance.
@@ -223,9 +243,27 @@ export class MCPDevice {
223
243
  return;
224
244
  }
225
245
  console.log(`🔧 Received tool call ${call_id}: ${tool_name} ${JSON.stringify(tool_args)} metadata: ${JSON.stringify(metadata)}`);
246
+ // LOCAL claim first — this is the authoritative guard against executing
247
+ // a call twice. During the transition both transports deliver every call
248
+ // to THIS SAME PROCESS, so an in-memory check is sufficient and, unlike
249
+ // the DB claim below, cannot fail open: a transient REST error made
250
+ // markCallExecuting return true for both deliveries, which could run a
251
+ // side-effecting command twice (found in review, 2026-07-24).
252
+ if (this.seenCallIds.has(call_id)) {
253
+ console.debug('[DEBUG] Duplicate delivery for call already handled here, skipping:', call_id);
254
+ return;
255
+ }
256
+ this.rememberCallId(call_id);
226
257
  try {
227
- // Update call status to executing
228
- await this.remoteChannel.markCallExecuting(call_id);
258
+ // DB claim second — keeps the row state machine honest, gives
259
+ // cross-restart/cross-process protection, and is observable. It may
260
+ // fail open (returns true on a transient write error); the local
261
+ // guard above is what makes execution exactly-once.
262
+ const claimed = await this.remoteChannel.markCallExecuting(call_id);
263
+ if (!claimed) {
264
+ // markCallExecuting already logged the duplicate-delivery skip.
265
+ return;
266
+ }
229
267
  let result;
230
268
  // Handle 'ping' tool specially
231
269
  if (tool_name === 'ping') {
@@ -255,13 +293,24 @@ export class MCPDevice {
255
293
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
256
294
  }
257
295
  console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
258
- // Update database with result
296
+ // Update database with result, THEN ring the doorbell — the server
297
+ // fetches the row by id on the doorbell, so the write must land first.
259
298
  await this.remoteChannel.updateCallResult(call_id, 'completed', result);
299
+ await this.remoteChannel.notifyResult(call_id);
260
300
  }
261
301
  catch (error) {
262
302
  console.error(`❌ Tool call ${tool_name} failed:`, error.message);
263
- await captureRemote('remote_device_tool_call_failed', { error, tool_name });
264
- await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
303
+ // The failure path must not fail: this method's promise is discarded
304
+ // at every call site, so a throw here becomes an unhandled rejection
305
+ // and takes the device process down.
306
+ try {
307
+ await captureRemote('remote_device_tool_call_failed', { error, tool_name });
308
+ await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
309
+ await this.remoteChannel.notifyResult(call_id);
310
+ }
311
+ catch (reportError) {
312
+ console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
313
+ }
265
314
  }
266
315
  }
267
316
  async shutdown() {
@@ -1,4 +1,10 @@
1
1
  import { Session, User } from '@supabase/supabase-js';
2
+ /**
3
+ * Strip NUL characters (U+0000) from strings and object keys — Postgres rejects
4
+ * them in jsonb and text (22P05). Walks the structure rather than
5
+ * round-tripping JSON, which would also match escape text in legitimate content.
6
+ */
7
+ export declare function stripNullBytes<T>(value: T): T;
2
8
  export interface AuthSession {
3
9
  access_token: string;
4
10
  refresh_token: string | null;
@@ -14,10 +20,31 @@ interface DeviceData {
14
20
  export declare class RemoteChannel {
15
21
  private client;
16
22
  private channel;
23
+ /** Legacy listener, on its own public channel so a private-channel auth
24
+ * failure can't take both transports down. Removed at the flip (009). */
25
+ private legacyChannel;
17
26
  private heartbeatInterval;
18
27
  private connectionCheckInterval;
28
+ /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
29
+ private heartbeatDeviceId;
30
+ private statusWriteChain;
31
+ /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
32
+ private lastKnownSession;
33
+ /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
34
+ * land after setOffline()'s durable write. */
35
+ private shuttingDown;
19
36
  private deviceId;
37
+ private deviceName;
20
38
  private onToolCall;
39
+ private authListenerRegistered;
40
+ /** False when presence publishing failed on an otherwise healthy channel;
41
+ * the health check retries, since SUBSCRIBED won't fire again. */
42
+ private presenceTracked;
43
+ /** Last capability value written (null = never), to avoid redundant writes. */
44
+ private transportCapableWritten;
45
+ /** Re-entrancy guard: on a wedged socket each track() buffers for the full
46
+ * 10s push timeout, so 10s health ticks would stack pushes. */
47
+ private isTrackingPresence;
21
48
  private lastDeviceStatus;
22
49
  private lastChannelState;
23
50
  private reconnectAttempt;
@@ -49,10 +76,48 @@ export declare class RemoteChannel {
49
76
  }>;
50
77
  registerDevice(capabilities: any, currentDeviceId: string | undefined, deviceName: string, onToolCall: (payload: any) => void): Promise<void>;
51
78
  /**
52
- * Create and subscribe to the channel.
53
- * This is used for both initial subscription and recreation after socket reconnects.
79
+ * Publish presence, retrying a non-'ok' result — track() resolves with a
80
+ * status rather than rejecting, and absent presence reads as offline on the
81
+ * server. `presenceTracked` lets the health check retry later.
54
82
  */
83
+ private trackPresenceWithRetry;
84
+ private trackPresenceInner;
85
+ /**
86
+ * The complete `capabilities` JSONB value. One place only: every write
87
+ * replaces the whole column, so a second literal would silently drop keys.
88
+ */
89
+ private capabilitiesPayload;
90
+ /**
91
+ * Advertise (or withdraw) the broadcast capability. Only true while genuinely
92
+ * reachable that way — the server uses it to pick a transport, to read absent
93
+ * presence as offline, and to choose the sweep tier, so every change must
94
+ * re-arm the heartbeat.
95
+ */
96
+ private setTransportCapable;
97
+ /**
98
+ * Legacy postgres_changes listener on its own public channel. Best-effort:
99
+ * failures are logged, never thrown. Removed at the flip (009).
100
+ */
101
+ private createLegacyChannel;
102
+ /** Tear down the legacy channel (best effort). */
103
+ private removeLegacyChannel;
104
+ /** Create and subscribe the private channel (initial join and recreation). */
55
105
  private createChannel;
106
+ /** Hand a call to device.ts, observing the rejection — the handler is async
107
+ * and an unhandled rejection terminates the process. */
108
+ private dispatchToolCall;
109
+ /**
110
+ * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
111
+ * primary key and fed through the same handler as a postgres_changes
112
+ * payload, so device.ts stays transport-agnostic.
113
+ */
114
+ private onDoorbell;
115
+ /**
116
+ * Tell the server a result row is written. Fire-and-forget: a failed send
117
+ * just falls back to the server's 10s recovery poll. MUST run only after
118
+ * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
119
+ */
120
+ notifyResult(callId: string): Promise<void>;
56
121
  /**
57
122
  * Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
58
123
  * readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),
@@ -68,15 +133,64 @@ export declare class RemoteChannel {
68
133
  * can't leave isRecreatingChannel stuck true and disable the watchdog. Mirrors
69
134
  * closeWithTimeout() in desktop-commander-integration.ts.
70
135
  */
136
+ private sleep;
137
+ /**
138
+ * Block until realtime-js has left the 'disconnecting' state it enters on
139
+ * disconnect(), so the next subscribe() actually dials a socket instead of
140
+ * hitting connect()'s early return. Bounded either way — worst case we cost
141
+ * a recreate SOCKET_SETTLE_MAX_MS.
142
+ */
143
+ private waitForSocketSettled;
71
144
  private withTimeout;
72
145
  /**
73
146
  * Recreate the channel by destroying old one and creating fresh instance.
74
147
  */
75
148
  private recreateChannel;
76
- markCallExecuting(callId: string): Promise<void>;
149
+ /**
150
+ * Claim a call. True only when THIS update flipped the row pending ->
151
+ * executing, which is what makes dual delivery safe across processes.
152
+ * .eq('status','pending') makes it conditional; .select('id') makes the
153
+ * result observable. On a transient DB error it returns true (execute
154
+ * anyway), matching prior behaviour — so device.ts's in-memory guard is what
155
+ * actually guarantees exactly-once within a process.
156
+ */
157
+ markCallExecuting(callId: string): Promise<boolean>;
77
158
  updateCallResult(callId: string, status: string, result?: any, errorMessage?: string | null): Promise<void>;
159
+ /**
160
+ * Reachable by SOME transport — the private channel or, during the
161
+ * transition, the independent legacy one. Gates the heartbeat and `status`:
162
+ * asking only about the private channel starves last_seen for a device whose
163
+ * legacy channel is fine, and the 45s sweep then blacks it out.
164
+ * Collapses to a single check at the flip (009).
165
+ */
166
+ private isReachable;
167
+ /**
168
+ * Set `status` from actual reachability. `status` is transport-agnostic (the
169
+ * server filters on it), so it must not follow one channel's health — the
170
+ * private channel's error path re-fires on every rejoin and would oscillate
171
+ * the row against the heartbeat. Same predicate as the heartbeat gate.
172
+ */
173
+ private syncReachabilityStatus;
174
+ /**
175
+ * Serialize the channel-callback status writes. They fire from un-awaited
176
+ * callbacks, and inside recreateChannel() a teardown's 'offline' and the
177
+ * fresh join's 'online' land ~100-300ms apart — unordered, 'offline' can win
178
+ * and leave a healthy device undispatchable until the next heartbeat.
179
+ *
180
+ * Not the single writer: updateHeartbeat, registerDevice and setOffline's
181
+ * subprocess write status directly, so this is not total ordering.
182
+ */
183
+ private queueStatusWrite;
184
+ /**
185
+ * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
186
+ * capability flag (what the server actually tiers its sweep on), not the
187
+ * build — see LEGACY_HEARTBEAT_INTERVAL.
188
+ */
189
+ private heartbeatIntervalMs;
78
190
  updateHeartbeat(deviceId: string): Promise<void>;
79
191
  startHeartbeat(deviceId: string): void;
192
+ /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
193
+ private scheduleHeartbeat;
80
194
  stopHeartbeat(): void;
81
195
  setOnlineStatus(deviceId: string, status: 'online' | 'offline'): Promise<void>;
82
196
  setOffline(deviceId: string | undefined): Promise<void>;