forked from wonderwhy-er/DesktopCommanderMCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrack-installation.js
More file actions
368 lines (326 loc) · 11.5 KB
/
track-installation.js
File metadata and controls
368 lines (326 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/env node
/**
* Installation Source Tracking Script
* Runs during npm install to detect how Desktop Commander was installed
*
* Debug logging can be enabled with:
* - DEBUG=desktop-commander npm install
* - DEBUG=* npm install
* - NODE_ENV=development npm install
* - DC_DEBUG=true npm install
*/
import { randomUUID } from 'crypto';
import * as https from 'https';
import { platform } from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
// Get current file directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Debug logging utility - configurable via environment variables
const DEBUG_ENABLED = process.env.DEBUG === 'desktop-commander' ||
process.env.DEBUG === '*' ||
process.env.NODE_ENV === 'development' ||
process.env.DC_DEBUG === 'true';
const debug = (...args) => {
if (DEBUG_ENABLED) {
console.log('[Desktop Commander Debug]', ...args);
}
};
const log = (...args) => {
// Always show important messages, but prefix differently for debug vs production
if (DEBUG_ENABLED) {
console.log('[Desktop Commander]', ...args);
}
};
/**
* Get the client ID from the Desktop Commander config file, or generate a new one
*/
async function getClientId() {
try {
const { homedir } = await import('os');
const { join } = await import('path');
const fs = await import('fs');
const USER_HOME = homedir();
const CONFIG_DIR = join(USER_HOME, '.claude-server-commander');
const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
// Try to read existing config
if (fs.existsSync(CONFIG_FILE)) {
const configData = fs.readFileSync(CONFIG_FILE, 'utf8');
const config = JSON.parse(configData);
if (config.clientId) {
debug(`Using existing clientId from config: ${config.clientId.substring(0, 8)}...`);
return config.clientId;
}
}
debug('No existing clientId found, generating new one');
// Fallback to random UUID if config doesn't exist or lacks clientId
return randomUUID();
} catch (error) {
debug(`Error reading config file: ${error.message}, using random UUID`);
// If anything goes wrong, fall back to random UUID
return randomUUID();
}
}
// Google Analytics configuration (same as setup script)
const GA_MEASUREMENT_ID = 'G-NGGDNL0K4L';
const GA_API_SECRET = '5M0mC--2S_6t94m8WrI60A';
const GA_BASE_URL = `https://www.google-analytics.com/mp/collect?measurement_id=${GA_MEASUREMENT_ID}&api_secret=${GA_API_SECRET}`;
/**
* Detect installation source from environment and process context
*/
async function detectInstallationSource() {
// Check npm environment variables for clues
const npmConfigUserAgent = process.env.npm_config_user_agent || '';
const npmExecpath = process.env.npm_execpath || '';
const npmCommand = process.env.npm_command || '';
const npmLifecycleEvent = process.env.npm_lifecycle_event || '';
// Check process arguments and parent commands
const processArgs = process.argv.join(' ');
const processTitle = process.title || '';
debug('Installation source detection...');
debug(`npm_config_user_agent: ${npmConfigUserAgent}`);
debug(`npm_execpath: ${npmExecpath}`);
debug(`npm_command: ${npmCommand}`);
debug(`npm_lifecycle_event: ${npmLifecycleEvent}`);
debug(`process.argv: ${processArgs}`);
debug(`process.title: ${processTitle}`);
// Try to get parent process information
let parentProcessInfo = null;
try {
const { execSync } = await import('child_process');
const ppid = process.ppid;
if (ppid && process.platform !== 'win32') {
// Get parent process command line on Unix systems
const parentCmd = execSync(`ps -p ${ppid} -o command=`, { encoding: 'utf8' }).trim();
parentProcessInfo = parentCmd;
debug(`parent process: ${parentCmd}`);
}
} catch (error) {
debug(`Could not get parent process info: ${error.message}`);
}
// Smithery detection - look for smithery in the process chain
const smitheryIndicators = [
npmConfigUserAgent.includes('smithery'),
npmExecpath.includes('smithery'),
processArgs.includes('smithery'),
processArgs.includes('@smithery/cli'),
processTitle.includes('smithery'),
parentProcessInfo && parentProcessInfo.includes('smithery'),
parentProcessInfo && parentProcessInfo.includes('@smithery/cli')
];
if (smitheryIndicators.some(indicator => indicator)) {
return {
source: 'smithery',
details: {
detection_method: 'process_chain',
user_agent: npmConfigUserAgent,
exec_path: npmExecpath,
command: npmCommand,
parent_process: parentProcessInfo || 'unknown',
process_args: processArgs
}
};
}
// Direct NPX usage
if (npmCommand === 'exec' || processArgs.includes('npx')) {
return {
source: 'npx-direct',
details: {
user_agent: npmConfigUserAgent,
command: npmCommand,
lifecycle_event: npmLifecycleEvent
}
};
}
// Regular npm install
if (npmCommand === 'install' || npmLifecycleEvent === 'postinstall') {
return {
source: 'npm-install',
details: {
user_agent: npmConfigUserAgent,
command: npmCommand,
lifecycle_event: npmLifecycleEvent
}
};
}
// GitHub Codespaces
if (process.env.CODESPACES) {
return {
source: 'github-codespaces',
details: {
codespace: process.env.CODESPACE_NAME || 'unknown'
}
};
}
// VS Code
if (process.env.VSCODE_PID || process.env.TERM_PROGRAM === 'vscode') {
return {
source: 'vscode',
details: {
term_program: process.env.TERM_PROGRAM,
vscode_pid: process.env.VSCODE_PID
}
};
}
// GitPod
if (process.env.GITPOD_WORKSPACE_ID) {
return {
source: 'gitpod',
details: {
workspace_id: process.env.GITPOD_WORKSPACE_ID.substring(0, 8) + '...' // Truncate for privacy
}
};
}
// CI/CD environments
if (process.env.CI) {
if (process.env.GITHUB_ACTIONS) {
return {
source: 'github-actions',
details: {
repository: process.env.GITHUB_REPOSITORY,
workflow: process.env.GITHUB_WORKFLOW
}
};
}
if (process.env.GITLAB_CI) {
return {
source: 'gitlab-ci',
details: {
project: process.env.CI_PROJECT_NAME
}
};
}
if (process.env.JENKINS_URL) {
return {
source: 'jenkins',
details: {
job: process.env.JOB_NAME
}
};
}
return {
source: 'ci-cd-other',
details: {
ci_env: 'unknown'
}
};
}
// Docker detection
if (process.env.DOCKER_CONTAINER) {
return {
source: 'docker',
details: {
container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown'
}
};
}
// Check for .dockerenv file (need to use fs import)
try {
const fs = await import('fs');
if (fs.existsSync('/.dockerenv')) {
return {
source: 'docker',
details: {
container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown'
}
};
}
} catch (error) {
// Ignore fs errors
}
// Default fallback
return {
source: 'unknown',
details: {
user_agent: npmConfigUserAgent || 'none',
command: npmCommand || 'none',
lifecycle: npmLifecycleEvent || 'none'
}
};
}
/**
* Send installation tracking to analytics
*/
async function trackInstallation(installationData) {
if (!GA_MEASUREMENT_ID || !GA_API_SECRET) {
debug('Analytics not configured, skipping tracking');
return;
}
try {
const uniqueUserId = await getClientId();
log("user id", uniqueUserId)
// Prepare GA4 payload
const payload = {
client_id: uniqueUserId,
non_personalized_ads: false,
timestamp_micros: Date.now() * 1000,
events: [{
name: 'package_installed',
params: {
timestamp: new Date().toISOString(),
platform: platform(),
installation_source: installationData.source,
installation_details: JSON.stringify(installationData.details),
package_name: '@wonderwhy-er/desktop-commander',
install_method: 'npm-lifecycle',
node_version: process.version,
npm_version: process.env.npm_version || 'unknown'
}
}]
};
const postData = JSON.stringify(payload);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
await new Promise((resolve, reject) => {
const req = https.request(GA_BASE_URL, options);
const timeoutId = setTimeout(() => {
req.destroy();
reject(new Error('Request timeout'));
}, 5000);
req.on('error', (error) => {
clearTimeout(timeoutId);
debug(`Analytics error: ${error.message}`);
resolve(); // Don't fail installation on analytics error
});
req.on('response', (res) => {
clearTimeout(timeoutId);
// Consume the response data to complete the request
res.on('data', () => {}); // Ignore response data
res.on('end', () => {
log(`Installation tracked: ${installationData.source}`);
resolve();
});
});
req.write(postData);
req.end();
});
} catch (error) {
debug(`Failed to track installation: ${error.message}`);
// Don't fail the installation process
}
}
/**
* Main execution
*/
async function main() {
try {
log('Package installation detected');
const installationData = await detectInstallationSource();
log(`Installation source: ${installationData.source}`);
await trackInstallation(installationData);
} catch (error) {
debug(`Installation tracking error: ${error.message}`);
// Don't fail the installation
}
}
// Only run if this script is executed directly (not imported)
if (import.meta.url === `file://${process.argv[1]}`) {
main();
}
export { detectInstallationSource, trackInstallation };