@wonderwhy-er/desktop-commander 0.2.46 → 0.2.48

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
 
@@ -1,7 +1,12 @@
1
1
  import { MCPDevice } from '../remote-device/device.js';
2
2
  import os from 'os';
3
3
  export async function runRemote() {
4
- const persistSession = process.argv.includes('--persist-session');
4
+ // --persist-session is kept as an accepted no-op so existing invocations
5
+ // and docs keep working; --no-persist-session opts back out.
6
+ const persistSession = !process.argv.includes('--no-persist-session');
7
+ if (!persistSession) {
8
+ console.log('🔓 Session persistence disabled — re-authorization required on every start');
9
+ }
5
10
  const disableNoSleep = process.argv.includes('--disable-no-sleep');
6
11
  const verbose = process.argv.includes('--debug');
7
12
  console.debug('[DEBUG] Verbose mode: ', verbose);
@@ -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,14 +7,28 @@ 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;
15
25
  this.isShuttingDown = false;
16
26
  this.configPath = path.join(os.homedir(), '.desktop-commander-device', 'device.json');
17
- this.persistSession = options.persistSession || false;
27
+ // Default ON. Off meant a full re-authorization on every start, and each
28
+ // one mints a fresh GoTrue session that nothing ever revokes; the orphaned
29
+ // refresh-token families get replayed, trip GoTrue's reuse detection, and
30
+ // take the whole family down including the token a healthy connector holds.
31
+ this.persistSession = options.persistSession ?? true;
18
32
  // Initialize desktop integration
19
33
  this.desktop = new DesktopCommanderIntegration();
20
34
  // Graceful shutdown handlers (only set once)
@@ -149,12 +163,21 @@ export class MCPDevice {
149
163
  const config = JSON.parse(data);
150
164
  this.deviceId = config?.deviceId;
151
165
  console.debug('[DEBUG] Loaded device ID:', this.deviceId);
152
- console.log('💾 Found persisted session for device ' + this.deviceId);
153
- if (config.session) {
166
+ if (config.session && this.persistSession) {
167
+ console.log('💾 Found persisted session for device ' + this.deviceId);
154
168
  console.debug('[DEBUG] Session found in config, returning session');
155
169
  return config.session;
156
170
  }
157
- console.debug('[DEBUG] No session in config');
171
+ // A previously saved session must not be reused on an opted-out run:
172
+ // it would skip the re-authorization the flag promises, and the save
173
+ // at the end of start() then discards a possibly-rotated refresh
174
+ // token — orphaning one more live server-side session.
175
+ if (config.session) {
176
+ console.debug('[DEBUG] Ignoring persisted session (--no-persist-session)');
177
+ }
178
+ else {
179
+ console.debug('[DEBUG] No session in config');
180
+ }
158
181
  return null;
159
182
  }
160
183
  catch (error) {
@@ -212,6 +235,16 @@ export class MCPDevice {
212
235
  };
213
236
  }
214
237
  // Methods moved to RemoteChannel
238
+ /** Record a handled call id, evicting the oldest once the cap is reached. */
239
+ rememberCallId(callId) {
240
+ this.seenCallIds.add(callId);
241
+ if (this.seenCallIds.size > SEEN_CALL_IDS_MAX) {
242
+ // Sets iterate in insertion order — drop the oldest entry.
243
+ const oldest = this.seenCallIds.values().next().value;
244
+ if (oldest !== undefined)
245
+ this.seenCallIds.delete(oldest);
246
+ }
247
+ }
215
248
  async handleNewToolCall(payload) {
216
249
  const toolCall = payload.new;
217
250
  // Expect toolCall to include a device_id field used to route calls to this device instance.
@@ -223,9 +256,27 @@ export class MCPDevice {
223
256
  return;
224
257
  }
225
258
  console.log(`🔧 Received tool call ${call_id}: ${tool_name} ${JSON.stringify(tool_args)} metadata: ${JSON.stringify(metadata)}`);
259
+ // LOCAL claim first — this is the authoritative guard against executing
260
+ // a call twice. During the transition both transports deliver every call
261
+ // to THIS SAME PROCESS, so an in-memory check is sufficient and, unlike
262
+ // the DB claim below, cannot fail open: a transient REST error made
263
+ // markCallExecuting return true for both deliveries, which could run a
264
+ // side-effecting command twice (found in review, 2026-07-24).
265
+ if (this.seenCallIds.has(call_id)) {
266
+ console.debug('[DEBUG] Duplicate delivery for call already handled here, skipping:', call_id);
267
+ return;
268
+ }
269
+ this.rememberCallId(call_id);
226
270
  try {
227
- // Update call status to executing
228
- await this.remoteChannel.markCallExecuting(call_id);
271
+ // DB claim second — keeps the row state machine honest, gives
272
+ // cross-restart/cross-process protection, and is observable. It may
273
+ // fail open (returns true on a transient write error); the local
274
+ // guard above is what makes execution exactly-once.
275
+ const claimed = await this.remoteChannel.markCallExecuting(call_id);
276
+ if (!claimed) {
277
+ // markCallExecuting already logged the duplicate-delivery skip.
278
+ return;
279
+ }
229
280
  let result;
230
281
  // Handle 'ping' tool specially
231
282
  if (tool_name === 'ping') {
@@ -255,13 +306,24 @@ export class MCPDevice {
255
306
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
256
307
  }
257
308
  console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
258
- // Update database with result
309
+ // Update database with result, THEN ring the doorbell — the server
310
+ // fetches the row by id on the doorbell, so the write must land first.
259
311
  await this.remoteChannel.updateCallResult(call_id, 'completed', result);
312
+ await this.remoteChannel.notifyResult(call_id);
260
313
  }
261
314
  catch (error) {
262
315
  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);
316
+ // The failure path must not fail: this method's promise is discarded
317
+ // at every call site, so a throw here becomes an unhandled rejection
318
+ // and takes the device process down.
319
+ try {
320
+ await captureRemote('remote_device_tool_call_failed', { error, tool_name });
321
+ await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
322
+ await this.remoteChannel.notifyResult(call_id);
323
+ }
324
+ catch (reportError) {
325
+ console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
326
+ }
265
327
  }
266
328
  }
267
329
  async shutdown() {
@@ -314,10 +376,12 @@ if (isMainModule) {
314
376
  // Parse command-line arguments
315
377
  const args = process.argv.slice(2);
316
378
  const options = {
317
- persistSession: args.includes('--persist-session')
379
+ // --persist-session is kept as an accepted no-op so existing invocations
380
+ // and docs keep working; --no-persist-session opts back out.
381
+ persistSession: !args.includes('--no-persist-session')
318
382
  };
319
- if (options.persistSession) {
320
- console.log('🔒 Session persistence enabled');
383
+ if (!options.persistSession) {
384
+ console.log('🔓 Session persistence disabled — re-authorization required on every start');
321
385
  }
322
386
  const device = new MCPDevice(options);
323
387
  device.start();
@@ -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;
@@ -11,24 +17,63 @@ interface DeviceData {
11
17
  status: string;
12
18
  last_seen: string;
13
19
  }
20
+ export declare function observeServerDate(dateHeader: string | null): void;
14
21
  export declare class RemoteChannel {
15
22
  private client;
16
23
  private channel;
17
24
  private heartbeatInterval;
18
25
  private connectionCheckInterval;
26
+ /** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
27
+ private heartbeatDeviceId;
28
+ private statusWriteChain;
29
+ /** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
30
+ private lastKnownSession;
31
+ /** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
32
+ * land after setOffline()'s durable write. */
33
+ private shuttingDown;
34
+ /** Auth session gone for good: stops rejoins and caps the notice at one line. */
35
+ private sessionLost;
36
+ private handlingSignedOut;
19
37
  private deviceId;
38
+ private deviceName;
20
39
  private onToolCall;
40
+ private authListenerRegistered;
41
+ /** False when presence publishing failed on an otherwise healthy channel;
42
+ * the health check retries, since SUBSCRIBED won't fire again. */
43
+ private presenceTracked;
44
+ /** Last capability value written (null = never), to avoid redundant writes. */
45
+ private transportCapableWritten;
46
+ /** Re-entrancy guard: on a wedged socket each track() buffers for the full
47
+ * 10s push timeout, so 10s health ticks would stack pushes. */
48
+ private isTrackingPresence;
21
49
  private lastDeviceStatus;
22
50
  private lastChannelState;
23
51
  private reconnectAttempt;
24
52
  private isRecreatingChannel;
25
53
  private joiningSince;
54
+ /** Last confirmed proof of life (SUBSCRIBED or heartbeat 'ok'); null until the
55
+ * first one lands. On performance.now(), not Date.now(): the clock-skew
56
+ * correction above can (un)patch Date.now mid-run, jumping wall-clock math by
57
+ * the whole offset — a backward jump would suppress stale detection for as
58
+ * long as the offset. Same for joiningSince. */
59
+ private lastHeartbeatOkAt;
60
+ private heartbeatListenerRegistered;
61
+ /** Our own fixed-cadence auth refresh timer — see TOKEN_REFRESH_INTERVAL_MS. */
62
+ private tokenRefreshInterval;
26
63
  private _user;
27
64
  get user(): User | null;
28
65
  initialize(url: string, key: string): void;
29
66
  setSession(session: AuthSession): Promise<{
30
67
  error: any;
31
68
  }>;
69
+ /**
70
+ * Session gone: one restore attempt, then go offline and stop retrying.
71
+ *
72
+ * The attempt matters because auth-js only treats network errors and 502/503/504
73
+ * as retryable — a 429 or 500 kills the session while the refresh token is fine.
74
+ * We don't re-authenticate: DeviceAuthenticator opens a browser and waits.
75
+ */
76
+ private handleSignedOut;
32
77
  getSession(): Promise<{
33
78
  data: {
34
79
  session: Session | null;
@@ -49,10 +94,41 @@ export declare class RemoteChannel {
49
94
  }>;
50
95
  registerDevice(capabilities: any, currentDeviceId: string | undefined, deviceName: string, onToolCall: (payload: any) => void): Promise<void>;
51
96
  /**
52
- * Create and subscribe to the channel.
53
- * This is used for both initial subscription and recreation after socket reconnects.
97
+ * Publish presence, retrying a non-'ok' result — track() resolves with a
98
+ * status rather than rejecting, and absent presence reads as offline on the
99
+ * server. `presenceTracked` lets the health check retry later.
100
+ */
101
+ private trackPresenceWithRetry;
102
+ private trackPresenceInner;
103
+ /**
104
+ * The complete `capabilities` JSONB value. One place only: every write
105
+ * replaces the whole column, so a second literal would silently drop keys.
106
+ */
107
+ private capabilitiesPayload;
108
+ /**
109
+ * Advertise (or withdraw) the broadcast capability. Only true while genuinely
110
+ * reachable that way — the server uses it to pick a transport, to read absent
111
+ * presence as offline, and to choose the sweep tier, so every change must
112
+ * re-arm the heartbeat.
54
113
  */
114
+ private setTransportCapable;
115
+ /** Create and subscribe the private channel (initial join and recreation). */
55
116
  private createChannel;
117
+ /** Hand a call to device.ts, observing the rejection — the handler is async
118
+ * and an unhandled rejection terminates the process. */
119
+ private dispatchToolCall;
120
+ /**
121
+ * Handle a 'new_call' doorbell. It carries ids only; the row is fetched by
122
+ * primary key and fed through the same handler as a postgres_changes
123
+ * payload, so device.ts stays transport-agnostic.
124
+ */
125
+ private onDoorbell;
126
+ /**
127
+ * Tell the server a result row is written. Fire-and-forget: a failed send
128
+ * just falls back to the server's 10s recovery poll. MUST run only after
129
+ * updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
130
+ */
131
+ notifyResult(callId: string): Promise<void>;
56
132
  /**
57
133
  * Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
58
134
  * readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),
@@ -68,15 +144,61 @@ export declare class RemoteChannel {
68
144
  * can't leave isRecreatingChannel stuck true and disable the watchdog. Mirrors
69
145
  * closeWithTimeout() in desktop-commander-integration.ts.
70
146
  */
147
+ private sleep;
148
+ /**
149
+ * Block until realtime-js has left the 'disconnecting' state it enters on
150
+ * disconnect(), so the next subscribe() actually dials a socket instead of
151
+ * hitting connect()'s early return. Bounded either way — worst case we cost
152
+ * a recreate SOCKET_SETTLE_MAX_MS.
153
+ */
154
+ private waitForSocketSettled;
71
155
  private withTimeout;
72
156
  /**
73
157
  * Recreate the channel by destroying old one and creating fresh instance.
74
158
  */
75
159
  private recreateChannel;
76
- markCallExecuting(callId: string): Promise<void>;
160
+ /**
161
+ * Claim a call. True only when THIS update flipped the row pending ->
162
+ * executing, which is what makes dual delivery safe across processes.
163
+ * .eq('status','pending') makes it conditional; .select('id') makes the
164
+ * result observable. On a transient DB error it returns true (execute
165
+ * anyway), matching prior behaviour — so device.ts's in-memory guard is what
166
+ * actually guarantees exactly-once within a process.
167
+ */
168
+ markCallExecuting(callId: string): Promise<boolean>;
77
169
  updateCallResult(callId: string, status: string, result?: any, errorMessage?: string | null): Promise<void>;
170
+ /** Reachable means the private channel is joined. Gates the heartbeat and `status`. */
171
+ private isReachable;
172
+ /**
173
+ * Set `status` from actual reachability. `status` is transport-agnostic (the
174
+ * server filters on it), so it must not follow one channel's health — the
175
+ * private channel's error path re-fires on every rejoin and would oscillate
176
+ * the row against the heartbeat. Same predicate as the heartbeat gate.
177
+ */
178
+ private syncReachabilityStatus;
179
+ /**
180
+ * Serialize the channel-callback status writes. They fire from un-awaited
181
+ * callbacks, and inside recreateChannel() a teardown's 'offline' and the
182
+ * fresh join's 'online' land ~100-300ms apart — unordered, 'offline' can win
183
+ * and leave a healthy device undispatchable until the next heartbeat.
184
+ *
185
+ * Not the single writer: updateHeartbeat, registerDevice and setOffline's
186
+ * subprocess write status directly, so this is not total ordering.
187
+ */
188
+ private queueStatusWrite;
189
+ /**
190
+ * Heartbeat cadence for the tier this device is CURRENTLY in. Follows the
191
+ * capability flag (what the server actually tiers its sweep on), not the
192
+ * build — see LEGACY_HEARTBEAT_INTERVAL.
193
+ */
194
+ private heartbeatIntervalMs;
78
195
  updateHeartbeat(deviceId: string): Promise<void>;
79
196
  startHeartbeat(deviceId: string): void;
197
+ private refreshTokenNow;
198
+ private startTokenRefresh;
199
+ private stopTokenRefresh;
200
+ /** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
201
+ private scheduleHeartbeat;
80
202
  stopHeartbeat(): void;
81
203
  setOnlineStatus(deviceId: string, status: 'online' | 'offline'): Promise<void>;
82
204
  setOffline(deviceId: string | undefined): Promise<void>;