tacticremote 1.6.6 → 1.8.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 DELETED
@@ -1,342 +0,0 @@
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
- const extraPaths = process.platform === 'darwin'
38
- ? ['/opt/homebrew/bin', '/usr/local/bin', '/opt/homebrew/sbin', '/usr/local/sbin']
39
- : ['/usr/local/bin'];
40
- const env = { ...process.env };
41
- const currentPath = env.PATH || '';
42
- const missing = extraPaths.filter(p => !currentPath.split(':').includes(p));
43
- if (missing.length) env.PATH = [...missing, currentPath].join(':');
44
-
45
- const result = spawnSync('which', [cmd], { env, timeout: 5000 });
46
- return result.status === 0;
47
- }
48
-
49
- class ClaudeRemoteServer {
50
- constructor(options = {}) {
51
- this.wss = null;
52
- this.httpServer = null;
53
- this.clients = new Map();
54
- this.externalClients = new Map();
55
- this.clientState = new Map();
56
- this.port = options.port || process.env.PORT || 8765;
57
- this.listenHost = options.listenHost || process.env.LISTEN_HOST || '0.0.0.0';
58
- this.allowedBasePath = options.allowedPath || process.env.CLAUDE_REMOTE_ALLOWED_PATH || os.homedir();
59
- this.currentPath = this.allowedBasePath;
60
- this.lastHookEvent = null;
61
- this.apiKey = options.apiKey || process.env.CLAUDE_REMOTE_API_KEY || null;
62
- this.wsHandler = null;
63
- this.heartbeatInterval = null;
64
- this._clientIdCounter = 0;
65
- this.managedSessions = new Set();
66
- this._onReady = options.onReady || null;
67
- }
68
-
69
- start() {
70
- // Set process working directory to user's path (not the server install directory)
71
- try { process.chdir(this.currentPath); } catch (_e) { /* ignore */ }
72
-
73
- this.setupProcessHandlers();
74
-
75
- // Initialize WebSocket handler
76
- this.wsHandler = createWsHandler(this);
77
-
78
- // Create HTTP server
79
- this.httpServer = http.createServer(
80
- createHttpHandler(this, this.handleHookEvent.bind(this))
81
- );
82
-
83
- // Create WebSocket server
84
- this.wss = new WebSocket.Server({
85
- server: this.httpServer,
86
- maxPayload: MAX_WS_PAYLOAD
87
- });
88
-
89
- this.wss.on('connection', (ws, req) => this.handleConnection(ws, req));
90
-
91
- // Suppress WS server error forwarding — we handle errors on httpServer
92
- this.wss.on('error', () => {});
93
-
94
- return new Promise((resolve, reject) => {
95
- this.httpServer.on('error', (err) => reject(err));
96
- this.httpServer.listen(this.port, this.listenHost, () => {
97
- this.startHeartbeat();
98
- if (this._onReady) this._onReady(this);
99
- resolve(this);
100
- });
101
- });
102
- }
103
-
104
- async stop() {
105
- if (this.heartbeatInterval) {
106
- clearInterval(this.heartbeatInterval);
107
- this.heartbeatInterval = null;
108
- }
109
- if (this.wsHandler && this.wsHandler.outputMonitors) {
110
- for (const [, monitor] of this.wsHandler.outputMonitors.entries()) {
111
- clearInterval(monitor.intervalId);
112
- }
113
- this.wsHandler.outputMonitors.clear();
114
- }
115
- const killed = [];
116
- if (this.managedSessions.size > 0) {
117
- const { killSession } = require('./lib/tmuxManager');
118
- for (const name of this.managedSessions) {
119
- try {
120
- await killSession(name);
121
- killed.push(name);
122
- } catch (_e) { /* best effort */ }
123
- }
124
- }
125
- authRateLimiter.destroy();
126
- if (this.httpServer) {
127
- this.httpServer.close();
128
- }
129
- return killed;
130
- }
131
-
132
- handleConnection(ws, req) {
133
- const clientIP = req.socket.remoteAddress || 'unknown';
134
- const isInternal = clientIP === '127.0.0.1' || clientIP === '::1' || clientIP === '::ffff:127.0.0.1';
135
-
136
- // Authentication
137
- if (this.apiKey) {
138
- const authResult = checkWsAuth(req, this.apiKey, clientIP);
139
- if (!authResult.authenticated) {
140
- const msg = authResult.rateLimited ? 'Too many failed attempts' : 'Unauthorized';
141
- console.log(`🔒 ${msg} from ${clientIP}`);
142
- ws.close(1008, msg);
143
- return;
144
- }
145
- console.log(`🔓 Authenticated connection from ${clientIP}`);
146
- }
147
-
148
- const clientId = `${Date.now()}-${++this._clientIdCounter}`;
149
- this.clients.set(clientId, ws);
150
- if (!isInternal) {
151
- this.externalClients.set(clientId, ws);
152
- }
153
- ws._clientId = clientId;
154
- ws._isInternal = isInternal;
155
-
156
- // Initialize per-client state
157
- this.clientState.set(clientId, {
158
- currentPath: this.currentPath
159
- });
160
-
161
- console.log(`✅ ${isInternal ? 'Internal' : 'iOS'} client connected: ${clientId} (${clientIP})`);
162
- this.emitClientCount();
163
-
164
- ws.isAlive = true;
165
- ws.on('pong', () => { ws.isAlive = true; });
166
-
167
- const capabilities = [];
168
- if (this.claudeAvailable) capabilities.push('structured_json');
169
- if (this.tmuxAvailable) capabilities.push('tmux');
170
-
171
- this.wsHandler.sendToClient(ws, {
172
- type: 'connected',
173
- path: this.clientState.get(clientId).currentPath,
174
- status: 'ready',
175
- capabilities
176
- });
177
-
178
- ws.on('message', (data) => {
179
- try {
180
- const message = JSON.parse(data.toString());
181
- this.wsHandler.handleMessage(ws, message);
182
- } catch (error) {
183
- console.error('Failed to parse message:', error);
184
- }
185
- });
186
-
187
- let connectionCleaned = false;
188
- const cleanupConnection = (reason) => {
189
- if (connectionCleaned) return;
190
- connectionCleaned = true;
191
- this.clients.delete(clientId);
192
- this.externalClients.delete(clientId);
193
- this.clientState.delete(clientId);
194
- if (this.wsHandler.cleanupClient) this.wsHandler.cleanupClient(ws);
195
- if (reason === 'close') {
196
- console.log(`❌ ${isInternal ? 'Internal' : 'iOS'} client disconnected: ${clientId}`);
197
- }
198
- this.emitClientCount();
199
- };
200
-
201
- ws.on('close', () => cleanupConnection('close'));
202
-
203
- ws.on('error', (error) => {
204
- console.error(`WebSocket error (${clientId}):`, error.message);
205
- cleanupConnection('error');
206
- });
207
- }
208
-
209
- /**
210
- * Emit a structured client count line for the Swift host to parse.
211
- * Format: __CLIENT_COUNT__:<external>:<total>
212
- */
213
- emitClientCount() {
214
- console.log(`__CLIENT_COUNT__:${this.externalClients.size}:${this.clients.size}`);
215
- }
216
-
217
- async handleHookEvent(hookData) {
218
- console.log(`🔔 Hook event: ${hookData.event} (${hookData.project})`);
219
-
220
- // Fallback: if hook didn't provide tmux_session, try to find it by matching project to session cwd
221
- if (!hookData.tmux_session && hookData.project) {
222
- try {
223
- const path = require('path');
224
- const { listSessions } = require('./lib/tmuxManager');
225
- const result = await listSessions();
226
- if (result && result.sessions) {
227
- const running = result.sessions.find(s => s.running && path.basename(s.path || '') === hookData.project);
228
- const match = running || result.sessions.find(s => path.basename(s.path || '') === hookData.project);
229
- if (match) {
230
- hookData.tmux_session = match.name;
231
- console.log(`[notify][hook] inferred tmux_session=${match.name} from project=${hookData.project}`);
232
- }
233
- }
234
- } catch (err) {
235
- console.warn(`[notify][hook] session inference failed: ${err.message}`);
236
- }
237
- }
238
-
239
- this.lastHookEvent = hookData;
240
-
241
- // Broadcast in both legacy and event-frame formats for compatibility.
242
- this.wsHandler.broadcast({
243
- type: 'hook_event',
244
- event: hookData.event,
245
- project: hookData.project,
246
- session: hookData.tmux_session,
247
- timestamp: hookData.timestamp
248
- });
249
- this.wsHandler.broadcastEvent('hook_event', {
250
- event: hookData.event,
251
- project: hookData.project,
252
- session: hookData.tmux_session,
253
- timestamp: hookData.timestamp
254
- });
255
-
256
- if (hookData.event === 'Stop') {
257
- console.log(`✅ Claude task completed in ${hookData.project}`);
258
- if (hookData.tmux_session) {
259
- this.wsHandler.captureAndBroadcast(hookData.tmux_session, 'completed');
260
- }
261
- }
262
-
263
- // PreToolUse / PostToolUse — broadcast structured tool data to iOS
264
- const hookEventName = hookData.hook_event_name || hookData.event;
265
- if (hookEventName === 'PreToolUse' || hookEventName === 'PostToolUse') {
266
- const toolEvent = {
267
- event: hookEventName,
268
- tool_name: hookData.tool_name,
269
- tool_use_id: hookData.tool_use_id,
270
- tool_detail: extractToolDetail(hookData.tool_name, hookData.tool_input),
271
- project: hookData.project,
272
- session: hookData.tmux_session,
273
- timestamp: hookData.timestamp || Date.now()
274
- };
275
- this.wsHandler.broadcastEvent('tool_use', toolEvent);
276
- }
277
-
278
- if (hookData.event === 'Notification' && hookData.data?.message) {
279
- this.wsHandler.broadcastEvent('notification', {
280
- title: 'Claude',
281
- body: hookData.data.message,
282
- project: hookData.project,
283
- session: hookData.tmux_session,
284
- event: 'notification',
285
- timestamp: hookData.timestamp
286
- });
287
- }
288
- }
289
-
290
- getLocalIP() {
291
- const interfaces = os.networkInterfaces();
292
- for (const name of Object.keys(interfaces)) {
293
- for (const iface of interfaces[name]) {
294
- if (iface.family === 'IPv4' && !iface.internal) {
295
- return iface.address;
296
- }
297
- }
298
- }
299
- return '127.0.0.1';
300
- }
301
-
302
- startHeartbeat() {
303
- this.heartbeatInterval = setInterval(() => {
304
- this.wss.clients.forEach((ws) => {
305
- if (ws.isAlive === false) {
306
- if (ws.missedHeartbeats === undefined) {
307
- ws.missedHeartbeats = 0;
308
- }
309
- ws.missedHeartbeats++;
310
- if (ws.missedHeartbeats >= 2) {
311
- console.log(`💔 Client heartbeat timeout, terminating (${ws._clientId || 'unknown'})`);
312
- return ws.terminate(); // triggers 'close' event -> cleanup + emitClientCount
313
- }
314
- } else {
315
- ws.missedHeartbeats = 0;
316
- }
317
- ws.isAlive = false;
318
- ws.ping();
319
- this.wsHandler.sendToClient(ws, { type: 'ping', timestamp: Date.now() });
320
- });
321
- }, 45000);
322
- }
323
-
324
- setupProcessHandlers() {
325
- process.on('unhandledRejection', (reason) => {
326
- console.error('Unhandled Promise Rejection:', reason);
327
- try {
328
- this.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
329
- } catch (_e) { /* ignore */ }
330
- });
331
-
332
- process.on('uncaughtException', (error) => {
333
- console.error('Uncaught Exception:', error);
334
- try {
335
- this.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
336
- } catch (_e) { /* ignore */ }
337
- setTimeout(() => process.exit(1), 1000);
338
- });
339
- }
340
- }
341
-
342
- module.exports = { ClaudeRemoteServer, checkCommand };