tacticremote 1.6.0 → 1.6.1

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.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Auth Challenge Manager
3
+ * Manages challenge-response lifecycle for sensitive directory access.
4
+ * Server sends auth_challenge events to iOS, iOS responds with auth_response.
5
+ * Grants are cached per-client per-sensitiveDir with a TTL.
6
+ *
7
+ * ⚠️ SYNC WARNING: This file is duplicated in Windows/server/lib/authChallengeManager.js.
8
+ * Any changes here must be mirrored there to keep both servers in sync.
9
+ */
10
+
11
+ const crypto = require('crypto');
12
+
13
+ const CHALLENGE_TIMEOUT = 30_000; // 30 seconds
14
+ const GRANT_TTL = 5 * 60_000; // 5 minutes
15
+
16
+ // pendingChallenges: Map<challengeId, { ws, resolve, reject, timer, path, sensitiveDir, method }>
17
+ const pendingChallenges = new Map();
18
+
19
+ // grantCache: Map<ws, Map<sensitiveDir, expiresAt>>
20
+ const grantCache = new Map();
21
+
22
+ // dedupe: Map<ws, Map<sensitiveDir, Promise>> — avoid duplicate prompts for same dir
23
+ const pendingByDir = new Map();
24
+
25
+ /**
26
+ * Check if a grant is still valid for this client + sensitiveDir
27
+ */
28
+ function isGranted(ws, sensitiveDir) {
29
+ const clientGrants = grantCache.get(ws);
30
+ if (!clientGrants) return false;
31
+ const expiresAt = clientGrants.get(sensitiveDir);
32
+ if (!expiresAt) return false;
33
+ if (Date.now() >= expiresAt) {
34
+ clientGrants.delete(sensitiveDir);
35
+ return false;
36
+ }
37
+ return true;
38
+ }
39
+
40
+ /**
41
+ * Add a grant for this client + sensitiveDir
42
+ */
43
+ function addGrant(ws, sensitiveDir) {
44
+ if (!grantCache.has(ws)) grantCache.set(ws, new Map());
45
+ grantCache.get(ws).set(sensitiveDir, Date.now() + GRANT_TTL);
46
+ }
47
+
48
+ /**
49
+ * Create an auth challenge and return a promise that resolves when the client responds.
50
+ * Deduplicates: if there's already a pending challenge for the same (ws, sensitiveDir),
51
+ * reuses the same promise.
52
+ *
53
+ * @returns {{ challengeId: string, expiresAt: number, promise: Promise<boolean> }}
54
+ */
55
+ function createChallenge(ws, path, sensitiveDir, method) {
56
+ // Dedupe: reuse existing pending challenge for same (ws, sensitiveDir)
57
+ if (!pendingByDir.has(ws)) pendingByDir.set(ws, new Map());
58
+ const dirMap = pendingByDir.get(ws);
59
+ if (dirMap.has(sensitiveDir)) {
60
+ const existing = dirMap.get(sensitiveDir);
61
+ return existing;
62
+ }
63
+
64
+ const challengeId = crypto.randomUUID();
65
+ const expiresAt = Date.now() + CHALLENGE_TIMEOUT;
66
+
67
+ const promise = new Promise((resolve, reject) => {
68
+ const timer = setTimeout(() => {
69
+ pendingChallenges.delete(challengeId);
70
+ dirMap.delete(sensitiveDir);
71
+ resolve(false); // timeout = denied
72
+ }, CHALLENGE_TIMEOUT);
73
+
74
+ pendingChallenges.set(challengeId, {
75
+ ws, resolve, reject, timer, path, sensitiveDir, method
76
+ });
77
+ });
78
+
79
+ const result = { challengeId, expiresAt, promise };
80
+ dirMap.set(sensitiveDir, result);
81
+
82
+ // Clean up dedupe entry when promise settles
83
+ promise.finally(() => {
84
+ dirMap.delete(sensitiveDir);
85
+ });
86
+
87
+ return result;
88
+ }
89
+
90
+ /**
91
+ * Resolve a pending challenge (called when iOS sends auth_response)
92
+ */
93
+ function resolveChallenge(challengeId, granted) {
94
+ const challenge = pendingChallenges.get(challengeId);
95
+ if (!challenge) return false;
96
+
97
+ clearTimeout(challenge.timer);
98
+ pendingChallenges.delete(challengeId);
99
+
100
+ if (granted) {
101
+ addGrant(challenge.ws, challenge.sensitiveDir);
102
+ }
103
+
104
+ challenge.resolve(granted);
105
+ return true;
106
+ }
107
+
108
+ /**
109
+ * Clean up all pending challenges and grants for a disconnected client
110
+ */
111
+ function cleanupClient(ws) {
112
+ // Clean pending challenges
113
+ for (const [challengeId, challenge] of pendingChallenges) {
114
+ if (challenge.ws === ws) {
115
+ clearTimeout(challenge.timer);
116
+ challenge.resolve(false);
117
+ pendingChallenges.delete(challengeId);
118
+ }
119
+ }
120
+ // Clean grants
121
+ grantCache.delete(ws);
122
+ // Clean dedupe
123
+ pendingByDir.delete(ws);
124
+ }
125
+
126
+ module.exports = {
127
+ createChallenge,
128
+ resolveChallenge,
129
+ isGranted,
130
+ addGrant,
131
+ cleanupClient,
132
+ CHALLENGE_TIMEOUT,
133
+ GRANT_TTL
134
+ };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Bonjour/mDNS service publisher
3
+ * Broadcasts the server on the local network so iPhone can discover it
4
+ * Uses bonjour-service (pure JS, works on Windows without native deps)
5
+ */
6
+
7
+ const os = require('os');
8
+
9
+ class BonjourPublisher {
10
+ constructor(port = 8765, apiKeyRequired = false, { silent = false } = {}) {
11
+ this.port = port;
12
+ this.apiKeyRequired = apiKeyRequired;
13
+ this.bonjour = null;
14
+ this.service = null;
15
+ this.silent = silent;
16
+ }
17
+
18
+ start() {
19
+ try {
20
+ const { Bonjour } = require('bonjour-service');
21
+ this.bonjour = new Bonjour();
22
+
23
+ const hostname = os.hostname().replace(/[^a-zA-Z0-9-]/g, '') || 'Windows';
24
+ this.service = this.bonjour.publish({
25
+ name: `ClaudeCodeRemote-${hostname}`,
26
+ type: 'ws',
27
+ protocol: 'tcp',
28
+ port: this.port,
29
+ txt: {
30
+ version: '1.0',
31
+ apiKeyRequired: this.apiKeyRequired ? 'true' : 'false',
32
+ platform: process.platform
33
+ }
34
+ });
35
+
36
+ if (!this.silent) console.log(`📡 Bonjour: Publishing _ws._tcp on port ${this.port}`);
37
+ } catch (error) {
38
+ if (!this.silent) console.warn('Bonjour publishing failed:', error.message);
39
+ }
40
+ }
41
+
42
+ stop() {
43
+ try {
44
+ if (this.service) {
45
+ this.service.stop();
46
+ this.service = null;
47
+ }
48
+ if (this.bonjour) {
49
+ this.bonjour.destroy();
50
+ this.bonjour = null;
51
+ }
52
+ if (!this.silent) console.log('📡 Bonjour: Stopped publishing');
53
+ } catch (error) {
54
+ console.warn('Bonjour stop error:', error.message);
55
+ }
56
+ }
57
+
58
+ updateTXTRecord(apiKeyRequired) {
59
+ this.apiKeyRequired = apiKeyRequired;
60
+ // bonjour-service doesn't support live TXT updates; restart
61
+ if (this.service) {
62
+ this.stop();
63
+ this.start();
64
+ }
65
+ }
66
+ }
67
+
68
+ module.exports = { BonjourPublisher };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Unified error codes for MacServer
3
+ * These codes are shared with iOS client for consistent error handling
4
+ */
5
+
6
+ const ErrorCodes = {
7
+ // Authentication errors
8
+ AUTH_FAILED: 'AUTH_FAILED',
9
+ AUTH_RATE_LIMITED: 'AUTH_RATE_LIMITED',
10
+
11
+ // Session errors
12
+ SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',
13
+ SESSION_INVALID_NAME: 'SESSION_INVALID_NAME',
14
+ SESSION_CREATE_FAILED: 'SESSION_CREATE_FAILED',
15
+
16
+ // Path errors
17
+ PATH_ACCESS_DENIED: 'PATH_ACCESS_DENIED',
18
+ PATH_NOT_FOUND: 'PATH_NOT_FOUND',
19
+ PATH_INVALID: 'PATH_INVALID',
20
+
21
+ // Command errors
22
+ COMMAND_INVALID: 'COMMAND_INVALID',
23
+ COMMAND_EXECUTION_FAILED: 'COMMAND_EXECUTION_FAILED',
24
+
25
+ // Connection errors
26
+ CONNECTION_TIMEOUT: 'CONNECTION_TIMEOUT',
27
+ CONNECTION_CLOSED: 'CONNECTION_CLOSED',
28
+
29
+ // Upload errors
30
+ UPLOAD_TOO_LARGE: 'UPLOAD_TOO_LARGE',
31
+ UPLOAD_INVALID_TYPE: 'UPLOAD_INVALID_TYPE',
32
+ UPLOAD_NOT_FOUND: 'UPLOAD_NOT_FOUND',
33
+ UPLOAD_CHUNK_ERROR: 'UPLOAD_CHUNK_ERROR',
34
+ UPLOAD_PATH_DENIED: 'UPLOAD_PATH_DENIED',
35
+
36
+ // General errors
37
+ INVALID_REQUEST: 'INVALID_REQUEST',
38
+ INTERNAL_ERROR: 'INTERNAL_ERROR',
39
+ RATE_LIMITED: 'RATE_LIMITED'
40
+ };
41
+
42
+ /**
43
+ * Create a structured error response
44
+ * @param {string} code - Error code from ErrorCodes
45
+ * @param {string} message - Human-readable error message
46
+ * @param {Object} details - Additional error details
47
+ * @returns {Object} Structured error object
48
+ */
49
+ function createError(code, message, details = {}) {
50
+ const error = {
51
+ type: 'error',
52
+ code,
53
+ error: message,
54
+ retryable: isRetryable(code),
55
+ ...details
56
+ };
57
+
58
+ // Convert retryAfter (seconds) to retryAfterMs (milliseconds)
59
+ if (details.retryAfter !== undefined) {
60
+ error.retryAfterMs = details.retryAfter * 1000;
61
+ }
62
+
63
+ return error;
64
+ }
65
+
66
+ /**
67
+ * Create a rate limit error with retry information
68
+ * @param {number} retryAfter - Seconds until retry is allowed
69
+ * @returns {Object} Rate limit error object
70
+ */
71
+ function createRateLimitError(retryAfter) {
72
+ return createError(
73
+ ErrorCodes.RATE_LIMITED,
74
+ 'Too many requests, please try again later',
75
+ { retryAfter }
76
+ );
77
+ }
78
+
79
+ /**
80
+ * Create a session not found error
81
+ * @param {string} sessionName - Name of the session that was not found
82
+ * @returns {Object} Session error object
83
+ */
84
+ function createSessionNotFoundError(sessionName) {
85
+ return createError(
86
+ ErrorCodes.SESSION_NOT_FOUND,
87
+ `Session not found: ${sessionName}`,
88
+ { session: sessionName }
89
+ );
90
+ }
91
+
92
+ /**
93
+ * Create a path access denied error
94
+ * @param {string} path - Path that was denied
95
+ * @returns {Object} Path error object
96
+ */
97
+ function createPathAccessDeniedError(path) {
98
+ return createError(
99
+ ErrorCodes.PATH_ACCESS_DENIED,
100
+ `Access denied to path: ${path}`,
101
+ { path }
102
+ );
103
+ }
104
+
105
+ /**
106
+ * Check if an error code is retryable
107
+ * @param {string} code - Error code to check
108
+ * @returns {boolean} Whether the error is retryable
109
+ */
110
+ function isRetryable(code) {
111
+ const retryableCodes = [
112
+ ErrorCodes.CONNECTION_TIMEOUT,
113
+ ErrorCodes.RATE_LIMITED,
114
+ ErrorCodes.AUTH_RATE_LIMITED,
115
+ ErrorCodes.INTERNAL_ERROR
116
+ ];
117
+ return retryableCodes.includes(code);
118
+ }
119
+
120
+ module.exports = {
121
+ ErrorCodes,
122
+ createError,
123
+ createRateLimitError,
124
+ createSessionNotFoundError,
125
+ createPathAccessDeniedError,
126
+ isRetryable
127
+ };
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Safe command execution module
3
+ * Uses spawn instead of exec to prevent command injection
4
+ */
5
+
6
+ const { spawn } = require('child_process');
7
+
8
+ /**
9
+ * Execute a command safely using spawn (no shell interpolation)
10
+ * @param {string} cmd - The command to execute
11
+ * @param {string[]} args - Array of arguments
12
+ * @param {object} opts - Options for spawn
13
+ * @param {number} [opts.timeout] - Timeout in ms (default 30000, 0 = no timeout)
14
+ * @param {number} [opts.maxBuffer] - Maximum bytes per stream before abort (default 2MB)
15
+ * @returns {Promise<string>} - stdout output
16
+ */
17
+ function execSafe(cmd, args = [], opts = {}) {
18
+ const { timeout = 30000, maxBuffer = 2 * 1024 * 1024, ...spawnOpts } = opts;
19
+
20
+ return new Promise((resolve, reject) => {
21
+ const child = spawn(cmd, args, {
22
+ shell: false,
23
+ ...spawnOpts
24
+ });
25
+
26
+ let stdout = '';
27
+ let stderr = '';
28
+ let timedOut = false;
29
+ let bufferExceeded = false;
30
+ let exceededStream = '';
31
+ let timer = null;
32
+
33
+ let killTimer = null;
34
+
35
+ if (timeout > 0) {
36
+ timer = setTimeout(() => {
37
+ timedOut = true;
38
+ child.kill('SIGTERM');
39
+ // Force kill after 5s grace period
40
+ killTimer = setTimeout(() => { try { child.kill('SIGKILL'); } catch (_e) { /* ignore */ } }, 5000);
41
+ }, timeout);
42
+ }
43
+
44
+ child.stdout.on('data', (data) => {
45
+ stdout += data.toString();
46
+ if (!bufferExceeded && stdout.length > maxBuffer) {
47
+ bufferExceeded = true;
48
+ exceededStream = 'stdout';
49
+ child.kill('SIGTERM');
50
+ }
51
+ });
52
+
53
+ child.stderr.on('data', (data) => {
54
+ stderr += data.toString();
55
+ if (!bufferExceeded && stderr.length > maxBuffer) {
56
+ bufferExceeded = true;
57
+ exceededStream = 'stderr';
58
+ child.kill('SIGTERM');
59
+ }
60
+ });
61
+
62
+ child.on('close', (code) => {
63
+ if (timer) clearTimeout(timer);
64
+ if (killTimer) clearTimeout(killTimer);
65
+ if (timedOut) {
66
+ const error = new Error(`Command timed out after ${timeout}ms: ${cmd} ${args.join(' ')}`);
67
+ error.code = 'ETIMEDOUT';
68
+ reject(error);
69
+ } else if (bufferExceeded) {
70
+ const error = new Error(`Command exceeded maxBuffer (${maxBuffer} bytes) on ${exceededStream}: ${cmd} ${args.join(' ')}`);
71
+ error.code = 'EMAXBUFFER';
72
+ error.stream = exceededStream;
73
+ reject(error);
74
+ } else if (code === 0) {
75
+ resolve(stdout.trim());
76
+ } else {
77
+ const error = new Error(stderr || `Command failed with code ${code}`);
78
+ error.code = code;
79
+ error.stderr = stderr;
80
+ reject(error);
81
+ }
82
+ });
83
+
84
+ child.on('error', (err) => {
85
+ if (timer) clearTimeout(timer);
86
+ if (killTimer) clearTimeout(killTimer);
87
+ reject(err);
88
+ });
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Execute tmux command safely
94
+ * @param {string} subCommand - tmux subcommand (e.g., 'send-keys', 'capture-pane')
95
+ * @param {string[]} args - Arguments for the subcommand
96
+ * @returns {Promise<string>}
97
+ */
98
+ function execTmux(subCommand, args = []) {
99
+ return execSafe('tmux', [subCommand, ...args]);
100
+ }
101
+
102
+ /**
103
+ * Check if tmux session exists
104
+ * @param {string} sessionName - Session name (must be pre-validated)
105
+ * @returns {Promise<boolean>}
106
+ */
107
+ async function tmuxSessionExists(sessionName) {
108
+ try {
109
+ await execTmux('has-session', ['-t', sessionName]);
110
+ return true;
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Capture tmux pane output
118
+ * @param {string} sessionName - Session name (must be pre-validated)
119
+ * @param {number} lines - Number of history lines to capture
120
+ * @returns {Promise<string>}
121
+ */
122
+ function tmuxCapture(sessionName, lines = 500) {
123
+ return execTmux('capture-pane', ['-t', sessionName, '-p', '-S', `-${lines}`]);
124
+ }
125
+
126
+ /**
127
+ * Send keys to tmux session
128
+ * @param {string} sessionName - Session name (must be pre-validated)
129
+ * @param {string[]} keys - Keys to send
130
+ * @returns {Promise<string>}
131
+ */
132
+ function tmuxSendKeys(sessionName, keys) {
133
+ return execTmux('send-keys', ['-t', sessionName, ...keys]);
134
+ }
135
+
136
+ /**
137
+ * Create new tmux session with large history buffer
138
+ * @param {string} sessionName - Session name (must be pre-validated)
139
+ * @param {string} workingDir - Working directory (must be pre-validated)
140
+ * @param {number} [cols] - Optional initial column count
141
+ * @param {number} [rows] - Optional initial row count
142
+ * @returns {Promise<string>}
143
+ */
144
+ async function tmuxNewSession(sessionName, workingDir, cols, rows) {
145
+ const args = ['-d', '-s', sessionName, '-c', workingDir];
146
+ if (cols && rows) {
147
+ args.push('-x', String(cols), '-y', String(rows));
148
+ }
149
+ await execTmux('new-session', args);
150
+ // Set large history-limit (50000 lines) for scrollback - essential for viewing Claude's long outputs
151
+ await execTmux('set-option', ['-t', sessionName, 'history-limit', '50000']);
152
+ }
153
+
154
+ /**
155
+ * Kill tmux session
156
+ * @param {string} sessionName - Session name (must be pre-validated)
157
+ * @returns {Promise<string>}
158
+ */
159
+ function tmuxKillSession(sessionName) {
160
+ return execTmux('kill-session', ['-t', sessionName]);
161
+ }
162
+
163
+ /**
164
+ * List tmux sessions
165
+ * @returns {Promise<string>}
166
+ */
167
+ function tmuxListSessions() {
168
+ return execTmux('list-sessions', ['-F', '#{session_name}:#{session_attached}:#{pane_current_path}']);
169
+ }
170
+
171
+ /**
172
+ * Get tmux pane current path
173
+ * @param {string} sessionName - Session name (must be pre-validated)
174
+ * @returns {Promise<string>}
175
+ */
176
+ function tmuxGetPanePath(sessionName) {
177
+ return execTmux('display-message', ['-t', sessionName, '-p', '#{pane_current_path}']);
178
+ }
179
+
180
+ /**
181
+ * Resize tmux window
182
+ * @param {string} sessionName - Session name (must be pre-validated)
183
+ * @param {number} cols - Number of columns
184
+ * @param {number} rows - Number of rows
185
+ * @returns {Promise<string>}
186
+ */
187
+ function tmuxResizeWindow(sessionName, cols, rows) {
188
+ return execTmux('resize-window', ['-t', sessionName, '-x', String(cols), '-y', String(rows)]);
189
+ }
190
+
191
+ module.exports = {
192
+ execSafe,
193
+ execTmux,
194
+ tmuxSessionExists,
195
+ tmuxCapture,
196
+ tmuxSendKeys,
197
+ tmuxNewSession,
198
+ tmuxKillSession,
199
+ tmuxListSessions,
200
+ tmuxGetPanePath,
201
+ tmuxResizeWindow
202
+ };
@@ -0,0 +1,177 @@
1
+ /**
2
+ * File system service for MacServer
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { execFileSync } = require('child_process');
8
+ const { validatePath } = require('./validators');
9
+ const { ErrorCodes, createError } = require('./errorCodes');
10
+
11
+ /**
12
+ * Change working directory
13
+ * @param {string} newPath - Path to change to
14
+ * @param {string} allowedBasePath - Base path restriction
15
+ * @param {string} currentPath - Current client path for resolving relative paths
16
+ * @returns {Object} Result with success status and path or error
17
+ */
18
+ function changePath(newPath, allowedBasePath, currentPath) {
19
+ const validation = validatePath(newPath, { allowedBasePath, currentPath });
20
+
21
+ if (!validation.valid) {
22
+ return {
23
+ success: false,
24
+ error: createError(ErrorCodes.PATH_INVALID, validation.error)
25
+ };
26
+ }
27
+
28
+ const expandedPath = validation.path;
29
+
30
+ if (!fs.existsSync(expandedPath)) {
31
+ return {
32
+ success: false,
33
+ error: createError(ErrorCodes.PATH_NOT_FOUND, `Path does not exist: ${newPath}`)
34
+ };
35
+ }
36
+
37
+ if (!fs.statSync(expandedPath).isDirectory()) {
38
+ return {
39
+ success: false,
40
+ error: createError(ErrorCodes.PATH_INVALID, `Not a directory: ${newPath}`)
41
+ };
42
+ }
43
+
44
+ return {
45
+ success: true,
46
+ path: expandedPath
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Create a new folder
52
+ * @param {string} folderPath - Path for new folder
53
+ * @param {string} allowedBasePath - Base path restriction
54
+ * @param {string} currentPath - Current client path for resolving relative paths
55
+ * @returns {Object} Result with success status
56
+ */
57
+ function createFolder(folderPath, allowedBasePath, currentPath) {
58
+ const validation = validatePath(folderPath, { allowedBasePath, currentPath });
59
+
60
+ if (!validation.valid) {
61
+ return {
62
+ success: false,
63
+ error: createError(ErrorCodes.PATH_INVALID, validation.error)
64
+ };
65
+ }
66
+
67
+ const expandedPath = validation.path;
68
+
69
+ if (fs.existsSync(expandedPath)) {
70
+ return {
71
+ success: false,
72
+ error: createError(ErrorCodes.PATH_INVALID, `Path already exists: ${folderPath}`)
73
+ };
74
+ }
75
+
76
+ try {
77
+ fs.mkdirSync(expandedPath, { recursive: true });
78
+ return {
79
+ success: true,
80
+ path: expandedPath
81
+ };
82
+ } catch (err) {
83
+ return {
84
+ success: false,
85
+ error: createError(ErrorCodes.PATH_ACCESS_DENIED, err.message)
86
+ };
87
+ }
88
+ }
89
+
90
+ /**
91
+ * List directory contents
92
+ * @param {string} dirPath - Directory to list
93
+ * @param {string} allowedBasePath - Base path restriction
94
+ * @param {string} currentPath - Current client path for resolving relative paths
95
+ * @returns {Object} Result with items or error
96
+ */
97
+ function listDirectory(dirPath, allowedBasePath, currentPath) {
98
+ const validation = validatePath(dirPath, { allowBrowse: true, allowedBasePath, currentPath });
99
+
100
+ if (!validation.valid) {
101
+ return {
102
+ success: false,
103
+ error: createError(ErrorCodes.PATH_INVALID, validation.error)
104
+ };
105
+ }
106
+
107
+ const expandedPath = validation.path;
108
+
109
+ if (!fs.existsSync(expandedPath)) {
110
+ return {
111
+ success: false,
112
+ error: createError(ErrorCodes.PATH_NOT_FOUND, `Directory does not exist: ${dirPath}`)
113
+ };
114
+ }
115
+
116
+ if (!fs.statSync(expandedPath).isDirectory()) {
117
+ return {
118
+ success: false,
119
+ error: createError(ErrorCodes.PATH_INVALID, `Not a directory: ${dirPath}`)
120
+ };
121
+ }
122
+
123
+ try {
124
+ const entries = fs.readdirSync(expandedPath, { withFileTypes: true });
125
+
126
+ const items = entries
127
+ .filter(entry => !entry.name.startsWith('.')) // Hide hidden files
128
+ .map(entry => ({
129
+ name: entry.name,
130
+ isDirectory: entry.isDirectory(),
131
+ path: path.join(expandedPath, entry.name)
132
+ }))
133
+ .sort((a, b) => {
134
+ // Directories first, then alphabetically
135
+ if (a.isDirectory && !b.isDirectory) return -1;
136
+ if (!a.isDirectory && b.isDirectory) return 1;
137
+ return a.name.localeCompare(b.name);
138
+ });
139
+
140
+ // Enrich items with git status
141
+ const gitStatusMap = {};
142
+ try {
143
+ const output = execFileSync('git', ['-C', expandedPath, 'status', '--short', '--porcelain'], { timeout: 3000, encoding: 'utf-8' });
144
+ for (const line of output.split('\n')) {
145
+ if (line.length < 4) continue;
146
+ const status = line.substring(0, 2).trim();
147
+ let filePath = line.substring(3).trim();
148
+ // For renames: "R old -> new", take the new path
149
+ if (filePath.includes(' -> ')) filePath = filePath.split(' -> ')[1];
150
+ const topLevel = filePath.split('/')[0];
151
+ if (status && topLevel) gitStatusMap[topLevel] = status;
152
+ }
153
+ } catch { /* not a git repo or git not available */ }
154
+
155
+ const enrichedItems = items.map(item => ({
156
+ ...item,
157
+ gitStatus: gitStatusMap[item.name] || null
158
+ }));
159
+
160
+ return {
161
+ success: true,
162
+ path: expandedPath,
163
+ items: enrichedItems
164
+ };
165
+ } catch (err) {
166
+ return {
167
+ success: false,
168
+ error: createError(ErrorCodes.PATH_ACCESS_DENIED, err.message)
169
+ };
170
+ }
171
+ }
172
+
173
+ module.exports = {
174
+ changePath,
175
+ createFolder,
176
+ listDirectory
177
+ };