tacticremote 1.7.0 → 1.8.2

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.
Files changed (49) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +32 -41
  3. package/bin/tacticremote.js +51 -99
  4. package/package.json +29 -42
  5. package/bin/tactic-remote-server.js +0 -636
  6. package/lib/authChallengeManager.js +0 -1
  7. package/lib/bonjourPublisher.js +0 -68
  8. package/lib/claudeSessionManager.js +0 -1
  9. package/lib/claudeTransport.js +0 -1
  10. package/lib/errorCodes.js +0 -1
  11. package/lib/execSafe.js +0 -1
  12. package/lib/fileService.js +0 -1
  13. package/lib/hookInstaller.js +0 -253
  14. package/lib/outputParser.js +0 -1
  15. package/lib/pushClient.js +0 -1
  16. package/lib/rateLimiter.js +0 -1
  17. package/lib/serverIdentity.js +0 -1
  18. package/lib/streamJsonParser.js +0 -1
  19. package/lib/tmuxManager.js +0 -1
  20. package/lib/uploadService.js +0 -1
  21. package/lib/validators.js +0 -1
  22. package/middleware/authMiddleware.js +0 -152
  23. package/routes/httpHandler.js +0 -111
  24. package/routes/wsHandler.js +0 -1094
  25. package/server.js +0 -236
  26. package/shared/server-core/authChallengeManager.js +0 -108
  27. package/shared/server-core/claudeSessionManager.js +0 -222
  28. package/shared/server-core/claudeTransport.js +0 -176
  29. package/shared/server-core/errorCodes.js +0 -91
  30. package/shared/server-core/execSafe.js +0 -185
  31. package/shared/server-core/fileService.js +0 -155
  32. package/shared/server-core/outputParser.js +0 -174
  33. package/shared/server-core/protocol-manifest.json +0 -59
  34. package/shared/server-core/protocol-manifest.schema.json +0 -90
  35. package/shared/server-core/protocolManifest.js +0 -42
  36. package/shared/server-core/pushClient.js +0 -198
  37. package/shared/server-core/rateLimiter.js +0 -98
  38. package/shared/server-core/serverConnectionLifecycle.js +0 -118
  39. package/shared/server-core/serverHandshake.js +0 -72
  40. package/shared/server-core/serverIdentity.js +0 -102
  41. package/shared/server-core/streamJsonParser.js +0 -321
  42. package/shared/server-core/tmuxManager.js +0 -596
  43. package/shared/server-core/unixProcessLifecycle.js +0 -96
  44. package/shared/server-core/unixServerHooks.js +0 -148
  45. package/shared/server-core/unixWsRuntime.js +0 -412
  46. package/shared/server-core/uploadService.js +0 -321
  47. package/shared/server-core/validators.js +0 -274
  48. package/shared/server-core/windowsServerHooks.js +0 -174
  49. package/shared/server-core/windowsWsRuntime.js +0 -413
package/server.js DELETED
@@ -1,236 +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
- const { extractToolDetail } = require('./lib/streamJsonParser');
18
- const pushClient = require('./lib/pushClient');
19
- const serverIdentity = require('./lib/serverIdentity');
20
- const { getForegroundMatchingClients, getLegacyExternalClients, handleUnixHookEvent } = require('./shared/server-core/unixServerHooks');
21
- const { emitClientCount, handleServerConnection, startServerHeartbeat } = require('./shared/server-core/serverConnectionLifecycle');
22
- const { buildServerHandshake } = require('./shared/server-core/serverHandshake');
23
- // NOTE: read `./package.json` (1.6.7), NOT `./package.npm.json` (1.6.0, stale thin wrapper).
24
- const { version: APP_VERSION } = require('./package.json');
25
-
26
- const MAX_WS_PAYLOAD = 512 * 1024; // 512KB
27
-
28
- /**
29
- * Check if required command is available
30
- */
31
- function checkCommand(cmd) {
32
- const { spawnSync } = require('child_process');
33
- const extraPaths = process.platform === 'darwin'
34
- ? ['/opt/homebrew/bin', '/usr/local/bin', '/opt/homebrew/sbin', '/usr/local/sbin']
35
- : ['/usr/local/bin'];
36
- const env = { ...process.env };
37
- const currentPath = env.PATH || '';
38
- const missing = extraPaths.filter(p => !currentPath.split(':').includes(p));
39
- if (missing.length) env.PATH = [...missing, currentPath].join(':');
40
-
41
- const result = spawnSync('which', [cmd], { env, timeout: 5000 });
42
- return result.status === 0;
43
- }
44
-
45
- class ClaudeRemoteServer {
46
- constructor(options = {}) {
47
- this.wss = null;
48
- this.httpServer = null;
49
- this.clients = new Map();
50
- this.externalClients = new Map();
51
- this.clientState = new Map();
52
- this.port = options.port || process.env.PORT || 8765;
53
- this.listenHost = options.listenHost || process.env.LISTEN_HOST || '0.0.0.0';
54
- this.allowedBasePath = options.allowedPath || process.env.CLAUDE_REMOTE_ALLOWED_PATH || os.homedir();
55
- this.currentPath = this.allowedBasePath;
56
- this.lastHookEvent = null;
57
- this.apiKey = options.apiKey || process.env.CLAUDE_REMOTE_API_KEY || null;
58
- this.wsHandler = null;
59
- this.heartbeatInterval = null;
60
- this._clientIdCounter = 0;
61
- this.managedSessions = new Set();
62
- this._onReady = options.onReady || null;
63
- this.tmuxAvailable = false;
64
- this.claudeAvailable = false;
65
- this.serverIdentity = null;
66
- this.pushEnabled = false;
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
- // Check available tools
74
- this.tmuxAvailable = checkCommand('tmux');
75
- this.claudeAvailable = checkCommand('claude');
76
-
77
- if (!this.tmuxAvailable && !this.claudeAvailable) {
78
- throw new Error('Neither tmux nor claude CLI found');
79
- }
80
-
81
- if (!this.tmuxAvailable) {
82
- console.log('⚠️ tmux not found — terminal mode disabled, structured JSON mode only');
83
- }
84
- if (!this.claudeAvailable) {
85
- console.log('⚠️ claude CLI not found — structured JSON mode disabled, terminal mode only');
86
- }
87
-
88
- // Load server identity and configure push client
89
- this.serverIdentity = serverIdentity.loadOrCreate();
90
- const pushServiceUrl = process.env.PUSH_SERVICE_URL;
91
- if (pushServiceUrl) {
92
- pushClient.configure(pushServiceUrl);
93
- this.pushEnabled = true;
94
- console.log(`🔔 Push notifications enabled → ${pushServiceUrl}`);
95
- }
96
-
97
- this.setupProcessHandlers();
98
-
99
- // Initialize WebSocket handler
100
- this.wsHandler = createWsHandler(this);
101
-
102
- // Create HTTP server
103
- this.httpServer = http.createServer(
104
- createHttpHandler(this, this.handleHookEvent.bind(this))
105
- );
106
-
107
- // Create WebSocket server
108
- this.wss = new WebSocket.Server({
109
- server: this.httpServer,
110
- maxPayload: MAX_WS_PAYLOAD
111
- });
112
-
113
- this.wss.on('connection', (ws, req) => this.handleConnection(ws, req));
114
-
115
- // Suppress WS server error forwarding — we handle errors on httpServer
116
- this.wss.on('error', () => {});
117
-
118
- return new Promise((resolve, reject) => {
119
- this.httpServer.on('error', (err) => reject(err));
120
- this.httpServer.listen(this.port, this.listenHost, () => {
121
- this.startHeartbeat();
122
- if (this._onReady) this._onReady(this);
123
- resolve(this);
124
- });
125
- });
126
- }
127
-
128
- async stop() {
129
- if (this.heartbeatInterval) {
130
- clearInterval(this.heartbeatInterval);
131
- this.heartbeatInterval = null;
132
- }
133
- if (this.wsHandler && this.wsHandler.outputMonitors) {
134
- for (const [, monitor] of this.wsHandler.outputMonitors.entries()) {
135
- clearInterval(monitor.intervalId);
136
- }
137
- this.wsHandler.outputMonitors.clear();
138
- }
139
- const killed = [];
140
- if (this.managedSessions.size > 0) {
141
- const { killSession } = require('./lib/tmuxManager');
142
- for (const name of this.managedSessions) {
143
- try {
144
- await killSession(name);
145
- killed.push(name);
146
- } catch (_e) { /* best effort */ }
147
- }
148
- }
149
- authRateLimiter.destroy();
150
- if (this.httpServer) {
151
- this.httpServer.close();
152
- }
153
- return killed;
154
- }
155
-
156
- handleConnection(ws, req) {
157
- handleServerConnection(this, ws, req, {
158
- checkWsAuth,
159
- generateClientId: () => `${Date.now()}-${++this._clientIdCounter}`,
160
- buildConnectedPayload: ({ clientState }) => {
161
- const capabilities = [];
162
- if (this.claudeAvailable) capabilities.push('structured_json');
163
- if (this.tmuxAvailable) capabilities.push('tmux');
164
- capabilities.push('client_state');
165
- if (this.pushEnabled) capabilities.push('register_push');
166
- capabilities.push('worktree');
167
-
168
- return {
169
- type: 'connected',
170
- path: clientState.currentPath,
171
- status: 'ready',
172
- capabilities,
173
- server: buildServerHandshake({
174
- platform: 'npm',
175
- appVersion: APP_VERSION
176
- })
177
- };
178
- }
179
- });
180
- }
181
-
182
- /**
183
- * Emit a structured client count line for the Swift host to parse.
184
- * Format: __CLIENT_COUNT__:<external>:<total>
185
- */
186
- emitClientCount() {
187
- emitClientCount(this);
188
- }
189
-
190
- getForegroundMatchingClients(sessionName) {
191
- return getForegroundMatchingClients(this, sessionName);
192
- }
193
-
194
- getLegacyExternalClients() {
195
- return getLegacyExternalClients(this);
196
- }
197
-
198
- async handleHookEvent(hookData) {
199
- return handleUnixHookEvent(this, hookData, { extractToolDetail });
200
- }
201
-
202
- getLocalIP() {
203
- const interfaces = os.networkInterfaces();
204
- for (const name of Object.keys(interfaces)) {
205
- for (const iface of interfaces[name]) {
206
- if (iface.family === 'IPv4' && !iface.internal) {
207
- return iface.address;
208
- }
209
- }
210
- }
211
- return '127.0.0.1';
212
- }
213
-
214
- startHeartbeat() {
215
- startServerHeartbeat(this);
216
- }
217
-
218
- setupProcessHandlers() {
219
- process.on('unhandledRejection', (reason) => {
220
- console.error('Unhandled Promise Rejection:', reason);
221
- try {
222
- this.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
223
- } catch (_e) { /* ignore */ }
224
- });
225
-
226
- process.on('uncaughtException', (error) => {
227
- console.error('Uncaught Exception:', error);
228
- try {
229
- this.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
230
- } catch (_e) { /* ignore */ }
231
- setTimeout(() => process.exit(1), 1000);
232
- });
233
- }
234
- }
235
-
236
- module.exports = { ClaudeRemoteServer, checkCommand };
@@ -1,108 +0,0 @@
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
-
8
- const crypto = require('crypto');
9
-
10
- const CHALLENGE_TIMEOUT = 30_000;
11
- const GRANT_TTL = 5 * 60_000;
12
-
13
- const pendingChallenges = new Map();
14
- const grantCache = new Map();
15
- const pendingByDir = new Map();
16
-
17
- function isGranted(ws, sensitiveDir) {
18
- const clientGrants = grantCache.get(ws);
19
- if (!clientGrants) return false;
20
- const expiresAt = clientGrants.get(sensitiveDir);
21
- if (!expiresAt) return false;
22
- if (Date.now() >= expiresAt) {
23
- clientGrants.delete(sensitiveDir);
24
- return false;
25
- }
26
- return true;
27
- }
28
-
29
- function addGrant(ws, sensitiveDir) {
30
- if (!grantCache.has(ws)) grantCache.set(ws, new Map());
31
- grantCache.get(ws).set(sensitiveDir, Date.now() + GRANT_TTL);
32
- }
33
-
34
- /**
35
- * Create an auth challenge and return a promise that resolves when the client responds.
36
- * Deduplicates: if there's already a pending challenge for the same (ws, sensitiveDir),
37
- * reuses the same promise.
38
- *
39
- * @returns {{ challengeId: string, expiresAt: number, promise: Promise<boolean> }}
40
- */
41
- function createChallenge(ws, path, sensitiveDir, method) {
42
- if (!pendingByDir.has(ws)) pendingByDir.set(ws, new Map());
43
- const dirMap = pendingByDir.get(ws);
44
- if (dirMap.has(sensitiveDir)) {
45
- return dirMap.get(sensitiveDir);
46
- }
47
-
48
- const challengeId = crypto.randomUUID();
49
- const expiresAt = Date.now() + CHALLENGE_TIMEOUT;
50
-
51
- const promise = new Promise((resolve, reject) => {
52
- const timer = setTimeout(() => {
53
- pendingChallenges.delete(challengeId);
54
- dirMap.delete(sensitiveDir);
55
- resolve(false);
56
- }, CHALLENGE_TIMEOUT);
57
-
58
- pendingChallenges.set(challengeId, {
59
- ws, resolve, reject, timer, path, sensitiveDir, method
60
- });
61
- });
62
-
63
- const result = { challengeId, expiresAt, promise };
64
- dirMap.set(sensitiveDir, result);
65
-
66
- promise.finally(() => {
67
- dirMap.delete(sensitiveDir);
68
- });
69
-
70
- return result;
71
- }
72
-
73
- function resolveChallenge(challengeId, granted) {
74
- const challenge = pendingChallenges.get(challengeId);
75
- if (!challenge) return false;
76
-
77
- clearTimeout(challenge.timer);
78
- pendingChallenges.delete(challengeId);
79
-
80
- if (granted) {
81
- addGrant(challenge.ws, challenge.sensitiveDir);
82
- }
83
-
84
- challenge.resolve(granted);
85
- return true;
86
- }
87
-
88
- function cleanupClient(ws) {
89
- for (const [challengeId, challenge] of pendingChallenges) {
90
- if (challenge.ws === ws) {
91
- clearTimeout(challenge.timer);
92
- challenge.resolve(false);
93
- pendingChallenges.delete(challengeId);
94
- }
95
- }
96
- grantCache.delete(ws);
97
- pendingByDir.delete(ws);
98
- }
99
-
100
- module.exports = {
101
- createChallenge,
102
- resolveChallenge,
103
- isGranted,
104
- addGrant,
105
- cleanupClient,
106
- CHALLENGE_TIMEOUT,
107
- GRANT_TTL
108
- };
@@ -1,222 +0,0 @@
1
- /**
2
- * ClaudeSessionManager — manages multiple structured Claude sessions.
3
- */
4
-
5
- const { randomUUID } = require('crypto');
6
- const { ClaudeTransport } = require('./claudeTransport');
7
- const { translateEvent } = require('./streamJsonParser');
8
-
9
- class ClaudeSessionManager {
10
- constructor({ broadcastToSubscribers, allowedBasePath }) {
11
- this.broadcastToSubscribers = broadcastToSubscribers;
12
- this.allowedBasePath = allowedBasePath;
13
- this.sessions = new Map();
14
- }
15
-
16
- createSession(cwd, ws, additionalArgs = []) {
17
- const sessionId = randomUUID();
18
-
19
- const transport = new ClaudeTransport({
20
- cwd,
21
- sessionId,
22
- additionalArgs
23
- });
24
-
25
- const entry = {
26
- transport,
27
- sessionId,
28
- cwd,
29
- subscribers: new Set([ws]),
30
- isRunning: false,
31
- pendingApprovalRequestId: null,
32
- createdAt: Date.now()
33
- };
34
-
35
- this.sessions.set(sessionId, entry);
36
-
37
- transport.on('json_event', (claudeEvent) => {
38
- const wsEvents = translateEvent(claudeEvent, sessionId);
39
- for (const wsEvent of wsEvents) {
40
- this.broadcastToSubscribers(entry.subscribers, wsEvent.event, wsEvent.payload);
41
-
42
- if (wsEvent.event === 'structured_init') {
43
- entry.isRunning = false;
44
- }
45
- if (wsEvent.event === 'structured_result') {
46
- entry.isRunning = false;
47
- entry.pendingApprovalRequestId = null;
48
- }
49
- if (wsEvent.event === 'structured_approval_request') {
50
- entry.pendingApprovalRequestId = wsEvent.payload.requestId || null;
51
- }
52
- }
53
- });
54
-
55
- transport.on('crash', ({ code, signal, stderr, reason }) => {
56
- console.error(`[StructuredSession] ${sessionId} crashed: code=${code} signal=${signal} reason=${reason}`);
57
- this.broadcastToSubscribers(entry.subscribers, 'structured_crash', {
58
- sessionId,
59
- code,
60
- signal,
61
- stderr: stderr ? stderr.substring(0, 500) : '',
62
- reason
63
- });
64
- entry.isRunning = false;
65
- this.sessions.delete(sessionId);
66
- });
67
-
68
- transport.on('shutdown', ({ clean }) => {
69
- this.broadcastToSubscribers(entry.subscribers, 'structured_shutdown', {
70
- sessionId,
71
- clean
72
- });
73
- entry.isRunning = false;
74
- this.sessions.delete(sessionId);
75
- });
76
-
77
- transport.start();
78
- return { sessionId, cwd };
79
- }
80
-
81
- sendMessage(sessionId, content) {
82
- const entry = this.sessions.get(sessionId);
83
- if (!entry) return false;
84
-
85
- const sent = entry.transport.send({
86
- type: 'user',
87
- message: {
88
- role: 'user',
89
- content
90
- }
91
- });
92
-
93
- if (sent) {
94
- entry.isRunning = true;
95
- }
96
-
97
- return sent;
98
- }
99
-
100
- respondApproval(sessionId, requestId, behavior, updatedInput, message) {
101
- const entry = this.sessions.get(sessionId);
102
- if (!entry) return false;
103
-
104
- const responsePayload = behavior === 'allow'
105
- ? { behavior: 'allow', updatedInput: updatedInput || {} }
106
- : { behavior: 'deny', message: message || 'User denied this action' };
107
-
108
- const sent = entry.transport.send({
109
- type: 'control_response',
110
- response: {
111
- subtype: 'success',
112
- request_id: requestId,
113
- response: responsePayload
114
- }
115
- });
116
-
117
- if (sent) {
118
- entry.pendingApprovalRequestId = null;
119
- }
120
-
121
- return sent;
122
- }
123
-
124
- steerMessage(sessionId, content) {
125
- const entry = this.sessions.get(sessionId);
126
- if (!entry) return false;
127
-
128
- return entry.transport.send({
129
- type: 'user',
130
- message: {
131
- role: 'user',
132
- content
133
- }
134
- });
135
- }
136
-
137
- hasPendingApproval(sessionId) {
138
- const entry = this.sessions.get(sessionId);
139
- if (!entry) return false;
140
- return entry.pendingApprovalRequestId != null;
141
- }
142
-
143
- hasAnyPendingApproval() {
144
- for (const [, entry] of this.sessions) {
145
- if (entry.pendingApprovalRequestId != null) return true;
146
- }
147
- return false;
148
- }
149
-
150
- stopSession(sessionId) {
151
- const entry = this.sessions.get(sessionId);
152
- if (!entry) return;
153
- entry.transport.shutdown();
154
- }
155
-
156
- destroySession(sessionId) {
157
- const entry = this.sessions.get(sessionId);
158
- if (!entry) return;
159
- entry.transport.shutdown();
160
- this.sessions.delete(sessionId);
161
- }
162
-
163
- addSubscriber(sessionId, ws) {
164
- const entry = this.sessions.get(sessionId);
165
- if (!entry) return false;
166
- entry.subscribers.add(ws);
167
- return true;
168
- }
169
-
170
- removeSubscriber(sessionId, ws) {
171
- const entry = this.sessions.get(sessionId);
172
- if (!entry) return;
173
- entry.subscribers.delete(ws);
174
- }
175
-
176
- removeSubscriberFromAll(ws) {
177
- for (const [, entry] of this.sessions) {
178
- entry.subscribers.delete(ws);
179
- }
180
- }
181
-
182
- getSession(sessionId) {
183
- const entry = this.sessions.get(sessionId);
184
- if (!entry) return null;
185
- return {
186
- sessionId: entry.sessionId,
187
- cwd: entry.cwd,
188
- isRunning: entry.isRunning,
189
- subscriberCount: entry.subscribers.size
190
- };
191
- }
192
-
193
- listSessions() {
194
- const result = [];
195
- for (const [, entry] of this.sessions) {
196
- result.push({
197
- sessionId: entry.sessionId,
198
- cwd: entry.cwd,
199
- isRunning: entry.isRunning
200
- });
201
- }
202
- return result;
203
- }
204
-
205
- async shutdownAll() {
206
- const promises = [];
207
- for (const [, entry] of this.sessions) {
208
- promises.push(new Promise((resolve) => {
209
- let resolved = false;
210
- const done = () => { if (!resolved) { resolved = true; resolve(); } };
211
- entry.transport.once('shutdown', done);
212
- entry.transport.once('crash', done);
213
- setTimeout(done, 12000);
214
- entry.transport.shutdown();
215
- }));
216
- }
217
- await Promise.all(promises);
218
- this.sessions.clear();
219
- }
220
- }
221
-
222
- module.exports = { ClaudeSessionManager };