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.
package/server.js ADDED
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Claude Code Remote Server v2
5
+ * WebSocket server + HTTP hook endpoint for iOS remote control
6
+ */
7
+
8
+ const WebSocket = require('ws');
9
+ const http = require('http');
10
+ const os = require('os');
11
+
12
+ // Modules
13
+ const { checkWsAuth, authRateLimiter } = require('./middleware/authMiddleware');
14
+ const { createHttpHandler } = require('./routes/httpHandler');
15
+ const { createWsHandler } = require('./routes/wsHandler');
16
+ const { ErrorCodes, createError } = require('./lib/errorCodes');
17
+
18
+ function extractToolDetail(toolName, toolInput) {
19
+ if (!toolInput || typeof toolInput !== 'object') return '';
20
+ switch (toolName) {
21
+ case 'Read': case 'Write': case 'Edit': return toolInput.file_path || '';
22
+ case 'Bash': return (toolInput.command || '').substring(0, 100);
23
+ case 'Glob': return toolInput.pattern || '';
24
+ case 'Grep': return toolInput.pattern || '';
25
+ case 'Agent': return toolInput.description || '';
26
+ default: return '';
27
+ }
28
+ }
29
+
30
+ const MAX_WS_PAYLOAD = 512 * 1024; // 512KB
31
+
32
+ /**
33
+ * Check if required command is available
34
+ */
35
+ function checkCommand(cmd) {
36
+ const { spawnSync } = require('child_process');
37
+ // Use 'which' instead of 'command -v' to avoid shell requirement
38
+ const result = spawnSync('which', [cmd]);
39
+ return result.status === 0;
40
+ }
41
+
42
+ class ClaudeRemoteServer {
43
+ constructor(options = {}) {
44
+ this.wss = null;
45
+ this.httpServer = null;
46
+ this.clients = new Map();
47
+ this.externalClients = new Map();
48
+ this.clientState = new Map();
49
+ this.port = options.port || process.env.PORT || 8765;
50
+ this.listenHost = options.listenHost || process.env.LISTEN_HOST || '0.0.0.0';
51
+ this.allowedBasePath = options.allowedPath || process.env.CLAUDE_REMOTE_ALLOWED_PATH || os.homedir();
52
+ this.currentPath = this.allowedBasePath;
53
+ this.lastHookEvent = null;
54
+ this.apiKey = options.apiKey || process.env.CLAUDE_REMOTE_API_KEY || null;
55
+ this.wsHandler = null;
56
+ this.heartbeatInterval = null;
57
+ this._clientIdCounter = 0;
58
+ this.managedSessions = new Set();
59
+ this._onReady = options.onReady || null;
60
+ }
61
+
62
+ start() {
63
+ // Set process working directory to user's path (not the server install directory)
64
+ try { process.chdir(this.currentPath); } catch (_e) { /* ignore */ }
65
+
66
+ this.setupProcessHandlers();
67
+
68
+ // Initialize WebSocket handler
69
+ this.wsHandler = createWsHandler(this);
70
+
71
+ // Create HTTP server
72
+ this.httpServer = http.createServer(
73
+ createHttpHandler(this, this.handleHookEvent.bind(this))
74
+ );
75
+
76
+ // Create WebSocket server
77
+ this.wss = new WebSocket.Server({
78
+ server: this.httpServer,
79
+ maxPayload: MAX_WS_PAYLOAD
80
+ });
81
+
82
+ this.wss.on('connection', (ws, req) => this.handleConnection(ws, req));
83
+
84
+ // Suppress WS server error forwarding — we handle errors on httpServer
85
+ this.wss.on('error', () => {});
86
+
87
+ return new Promise((resolve, reject) => {
88
+ this.httpServer.on('error', (err) => reject(err));
89
+ this.httpServer.listen(this.port, this.listenHost, () => {
90
+ this.startHeartbeat();
91
+ if (this._onReady) this._onReady(this);
92
+ resolve(this);
93
+ });
94
+ });
95
+ }
96
+
97
+ async stop() {
98
+ if (this.heartbeatInterval) {
99
+ clearInterval(this.heartbeatInterval);
100
+ this.heartbeatInterval = null;
101
+ }
102
+ if (this.wsHandler && this.wsHandler.outputMonitors) {
103
+ for (const [, monitor] of this.wsHandler.outputMonitors.entries()) {
104
+ clearInterval(monitor.intervalId);
105
+ }
106
+ this.wsHandler.outputMonitors.clear();
107
+ }
108
+ const killed = [];
109
+ if (this.managedSessions.size > 0) {
110
+ const { killSession } = require('./lib/tmuxManager');
111
+ for (const name of this.managedSessions) {
112
+ try {
113
+ await killSession(name);
114
+ killed.push(name);
115
+ } catch (_e) { /* best effort */ }
116
+ }
117
+ }
118
+ authRateLimiter.destroy();
119
+ if (this.httpServer) {
120
+ this.httpServer.close();
121
+ }
122
+ return killed;
123
+ }
124
+
125
+ handleConnection(ws, req) {
126
+ const clientIP = req.socket.remoteAddress || 'unknown';
127
+ const isInternal = clientIP === '127.0.0.1' || clientIP === '::1' || clientIP === '::ffff:127.0.0.1';
128
+
129
+ // Authentication
130
+ if (this.apiKey) {
131
+ const authResult = checkWsAuth(req, this.apiKey, clientIP);
132
+ if (!authResult.authenticated) {
133
+ const msg = authResult.rateLimited ? 'Too many failed attempts' : 'Unauthorized';
134
+ console.log(`🔒 ${msg} from ${clientIP}`);
135
+ ws.close(1008, msg);
136
+ return;
137
+ }
138
+ console.log(`🔓 Authenticated connection from ${clientIP}`);
139
+ }
140
+
141
+ const clientId = `${Date.now()}-${++this._clientIdCounter}`;
142
+ this.clients.set(clientId, ws);
143
+ if (!isInternal) {
144
+ this.externalClients.set(clientId, ws);
145
+ }
146
+ ws._clientId = clientId;
147
+ ws._isInternal = isInternal;
148
+
149
+ // Initialize per-client state
150
+ this.clientState.set(clientId, {
151
+ currentPath: this.currentPath
152
+ });
153
+
154
+ console.log(`✅ ${isInternal ? 'Internal' : 'iOS'} client connected: ${clientId} (${clientIP})`);
155
+ this.emitClientCount();
156
+
157
+ ws.isAlive = true;
158
+ ws.on('pong', () => { ws.isAlive = true; });
159
+
160
+ this.wsHandler.sendToClient(ws, {
161
+ type: 'connected',
162
+ path: this.clientState.get(clientId).currentPath,
163
+ status: 'ready'
164
+ });
165
+
166
+ ws.on('message', (data) => {
167
+ try {
168
+ const message = JSON.parse(data.toString());
169
+ this.wsHandler.handleMessage(ws, message);
170
+ } catch (error) {
171
+ console.error('Failed to parse message:', error);
172
+ }
173
+ });
174
+
175
+ let connectionCleaned = false;
176
+ const cleanupConnection = (reason) => {
177
+ if (connectionCleaned) return;
178
+ connectionCleaned = true;
179
+ this.clients.delete(clientId);
180
+ this.externalClients.delete(clientId);
181
+ this.clientState.delete(clientId);
182
+ if (this.wsHandler.cleanupClient) this.wsHandler.cleanupClient(ws);
183
+ if (reason === 'close') {
184
+ console.log(`❌ ${isInternal ? 'Internal' : 'iOS'} client disconnected: ${clientId}`);
185
+ }
186
+ this.emitClientCount();
187
+ };
188
+
189
+ ws.on('close', () => cleanupConnection('close'));
190
+
191
+ ws.on('error', (error) => {
192
+ console.error(`WebSocket error (${clientId}):`, error.message);
193
+ cleanupConnection('error');
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Emit a structured client count line for the Swift host to parse.
199
+ * Format: __CLIENT_COUNT__:<external>:<total>
200
+ */
201
+ emitClientCount() {
202
+ console.log(`__CLIENT_COUNT__:${this.externalClients.size}:${this.clients.size}`);
203
+ }
204
+
205
+ handleHookEvent(hookData) {
206
+ console.log(`🔔 Hook event: ${hookData.event} (${hookData.project})`);
207
+ this.lastHookEvent = hookData;
208
+
209
+ // Broadcast in both legacy and event-frame formats for compatibility.
210
+ this.wsHandler.broadcast({
211
+ type: 'hook_event',
212
+ event: hookData.event,
213
+ project: hookData.project,
214
+ session: hookData.tmux_session,
215
+ timestamp: hookData.timestamp
216
+ });
217
+ this.wsHandler.broadcastEvent('hook_event', {
218
+ event: hookData.event,
219
+ project: hookData.project,
220
+ session: hookData.tmux_session,
221
+ timestamp: hookData.timestamp
222
+ });
223
+
224
+ if (hookData.event === 'Stop') {
225
+ console.log(`✅ Claude task completed in ${hookData.project}`);
226
+ if (hookData.tmux_session) {
227
+ this.wsHandler.captureAndBroadcast(hookData.tmux_session, 'completed');
228
+ }
229
+ }
230
+
231
+ // PreToolUse / PostToolUse — broadcast structured tool data to iOS
232
+ const hookEventName = hookData.hook_event_name || hookData.event;
233
+ if (hookEventName === 'PreToolUse' || hookEventName === 'PostToolUse') {
234
+ const toolEvent = {
235
+ event: hookEventName,
236
+ tool_name: hookData.tool_name,
237
+ tool_use_id: hookData.tool_use_id,
238
+ tool_detail: extractToolDetail(hookData.tool_name, hookData.tool_input),
239
+ project: hookData.project,
240
+ session: hookData.tmux_session,
241
+ timestamp: hookData.timestamp || Date.now()
242
+ };
243
+ this.wsHandler.broadcastEvent('tool_use', toolEvent);
244
+ }
245
+
246
+ if (hookData.event === 'Notification' && hookData.data?.message) {
247
+ this.wsHandler.broadcastEvent('notification', {
248
+ title: 'Claude',
249
+ body: hookData.data.message,
250
+ project: hookData.project,
251
+ event: 'notification',
252
+ timestamp: hookData.timestamp
253
+ });
254
+ }
255
+ }
256
+
257
+ getLocalIP() {
258
+ const interfaces = os.networkInterfaces();
259
+ for (const name of Object.keys(interfaces)) {
260
+ for (const iface of interfaces[name]) {
261
+ if (iface.family === 'IPv4' && !iface.internal) {
262
+ return iface.address;
263
+ }
264
+ }
265
+ }
266
+ return '127.0.0.1';
267
+ }
268
+
269
+ startHeartbeat() {
270
+ this.heartbeatInterval = setInterval(() => {
271
+ this.wss.clients.forEach((ws) => {
272
+ if (ws.isAlive === false) {
273
+ if (ws.missedHeartbeats === undefined) {
274
+ ws.missedHeartbeats = 0;
275
+ }
276
+ ws.missedHeartbeats++;
277
+ if (ws.missedHeartbeats >= 2) {
278
+ console.log(`💔 Client heartbeat timeout, terminating (${ws._clientId || 'unknown'})`);
279
+ return ws.terminate(); // triggers 'close' event -> cleanup + emitClientCount
280
+ }
281
+ } else {
282
+ ws.missedHeartbeats = 0;
283
+ }
284
+ ws.isAlive = false;
285
+ ws.ping();
286
+ this.wsHandler.sendToClient(ws, { type: 'ping', timestamp: Date.now() });
287
+ });
288
+ }, 45000);
289
+ }
290
+
291
+ setupProcessHandlers() {
292
+ process.on('unhandledRejection', (reason) => {
293
+ console.error('Unhandled Promise Rejection:', reason);
294
+ try {
295
+ this.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
296
+ } catch (_e) { /* ignore */ }
297
+ });
298
+
299
+ process.on('uncaughtException', (error) => {
300
+ console.error('Uncaught Exception:', error);
301
+ try {
302
+ this.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
303
+ } catch (_e) { /* ignore */ }
304
+ setTimeout(() => process.exit(1), 1000);
305
+ });
306
+ }
307
+ }
308
+
309
+ module.exports = { ClaudeRemoteServer, checkCommand };