tacticremote 1.6.0 → 1.6.5

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,152 @@
1
+ /**
2
+ * Authentication middleware for MacServer
3
+ */
4
+
5
+ const crypto = require('crypto');
6
+ const { RateLimiter } = require('../lib/rateLimiter');
7
+ const { ErrorCodes, createError } = require('../lib/errorCodes');
8
+
9
+ // Rate limiter for failed auth attempts (30 per minute per IP)
10
+ const authRateLimiter = new RateLimiter({
11
+ windowMs: 60 * 1000,
12
+ maxAttempts: 30
13
+ });
14
+
15
+ /**
16
+ * Timing-safe comparison of two strings.
17
+ * Prevents timing side-channel attacks on API key verification.
18
+ */
19
+ function timingSafeEqual(a, b) {
20
+ const aBuf = Buffer.from(String(a));
21
+ const bBuf = Buffer.from(String(b));
22
+ if (aBuf.length !== bBuf.length) {
23
+ // Compare against self so we still spend constant time
24
+ crypto.timingSafeEqual(aBuf, aBuf);
25
+ return false;
26
+ }
27
+ return crypto.timingSafeEqual(aBuf, bBuf);
28
+ }
29
+
30
+ /**
31
+ * Check HTTP request authentication
32
+ * @param {Object} req - HTTP request
33
+ * @param {string} apiKey - Expected API key
34
+ * @returns {Object} Authentication result
35
+ */
36
+ function checkHttpAuth(req, apiKey) {
37
+ const clientIP = req.socket.remoteAddress || 'unknown';
38
+
39
+ if (!apiKey) {
40
+ return { authenticated: true };
41
+ }
42
+
43
+ // Check rate limit first
44
+ if (!authRateLimiter.isAllowed(clientIP)) {
45
+ const resetTime = authRateLimiter.getResetTime(clientIP);
46
+ return {
47
+ authenticated: false,
48
+ rateLimited: true,
49
+ resetTime
50
+ };
51
+ }
52
+
53
+ // Support both X-API-Key header and Authorization Bearer
54
+ const xApiKey = req.headers['x-api-key'] || '';
55
+ const authHeader = req.headers['authorization'] || '';
56
+
57
+ let providedKey = xApiKey;
58
+ if (!providedKey && authHeader.startsWith('Bearer ')) {
59
+ providedKey = authHeader.slice(7);
60
+ }
61
+
62
+ if (timingSafeEqual(providedKey, apiKey)) {
63
+ return { authenticated: true };
64
+ }
65
+
66
+ // Record failed attempt
67
+ authRateLimiter.recordFailure(clientIP);
68
+ return {
69
+ authenticated: false,
70
+ rateLimited: false,
71
+ remaining: authRateLimiter.getRemainingAttempts(clientIP)
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Check WebSocket connection authentication
77
+ * @param {Object} req - HTTP upgrade request
78
+ * @param {string} apiKey - Expected API key
79
+ * @param {string} clientIP - Client IP address
80
+ * @returns {Object} Authentication result
81
+ */
82
+ function checkWsAuth(req, apiKey, clientIP) {
83
+ if (!apiKey) {
84
+ return { authenticated: true };
85
+ }
86
+
87
+ // Check rate limit first
88
+ if (!authRateLimiter.isAllowed(clientIP)) {
89
+ const resetTime = authRateLimiter.getResetTime(clientIP);
90
+ return {
91
+ authenticated: false,
92
+ rateLimited: true,
93
+ resetTime
94
+ };
95
+ }
96
+
97
+ // Support both Authorization header (Bearer) and sec-websocket-protocol
98
+ const authHeader = req.headers['authorization'] || '';
99
+ const protocolKey = req.headers['sec-websocket-protocol'] || '';
100
+
101
+ let providedKey = '';
102
+ if (authHeader.startsWith('Bearer ')) {
103
+ providedKey = authHeader.slice(7);
104
+ } else {
105
+ providedKey = protocolKey;
106
+ }
107
+
108
+ if (timingSafeEqual(providedKey, apiKey)) {
109
+ return { authenticated: true };
110
+ }
111
+
112
+ // Record failed attempt
113
+ authRateLimiter.recordFailure(clientIP);
114
+ return {
115
+ authenticated: false,
116
+ rateLimited: false,
117
+ remaining: authRateLimiter.getRemainingAttempts(clientIP)
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Send authentication error response
123
+ * @param {Object} res - HTTP response
124
+ * @param {Object} authResult - Authentication result from checkHttpAuth
125
+ * @param {string} clientIP - Client IP for logging
126
+ * @param {string} endpoint - Endpoint name for logging
127
+ */
128
+ function sendAuthError(res, authResult, clientIP, endpoint) {
129
+ if (authResult.rateLimited) {
130
+ console.log(`🚫 Rate limited ${endpoint} request from ${clientIP}`);
131
+ res.writeHead(429, { 'Content-Type': 'application/json' });
132
+ res.end(JSON.stringify(createError(
133
+ ErrorCodes.AUTH_RATE_LIMITED,
134
+ 'Too many failed attempts',
135
+ { retryAfter: authResult.resetTime }
136
+ )));
137
+ } else {
138
+ console.log(`🔒 Unauthorized ${endpoint} request from ${clientIP} (${authResult.remaining} attempts remaining)`);
139
+ res.writeHead(401, { 'Content-Type': 'application/json' });
140
+ res.end(JSON.stringify(createError(
141
+ ErrorCodes.AUTH_FAILED,
142
+ 'Unauthorized'
143
+ )));
144
+ }
145
+ }
146
+
147
+ module.exports = {
148
+ authRateLimiter,
149
+ checkHttpAuth,
150
+ checkWsAuth,
151
+ sendAuthError
152
+ };
package/package.json CHANGED
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "tacticremote",
3
- "version": "1.6.0",
4
- "description": "Control Claude Code from your iPhone/iPad — Tactic Remote server",
3
+ "version": "1.6.5",
4
+ "description": "Control Claude Code from your iPhone/iPad — server for Tactic Remote",
5
5
  "bin": {
6
- "tacticremote": "./bin/tacticremote.js"
6
+ "tacticremote": "./bin/tactic-remote-server.js"
7
7
  },
8
- "files": [
9
- "bin/tacticremote.js"
10
- ],
11
- "engines": {
12
- "node": ">=16.0.0"
8
+ "main": "server.js",
9
+ "scripts": {
10
+ "start": "node bin/tactic-remote-server.js",
11
+ "test": "jest --no-cache",
12
+ "lint": "eslint .",
13
+ "format": "prettier --write ."
13
14
  },
14
15
  "keywords": [
15
16
  "claude-code",
@@ -31,5 +32,27 @@
31
32
  "homepage": "https://tacticremote.com",
32
33
  "bugs": {
33
34
  "url": "https://github.com/TacticSpaceTech/TacticRemote/issues"
34
- }
35
+ },
36
+ "engines": {
37
+ "node": ">=16.0.0"
38
+ },
39
+ "dependencies": {
40
+ "ws": "^8.14.2",
41
+ "bonjour-service": "^1.2.1",
42
+ "qrcode-terminal": "^0.12.0"
43
+ },
44
+ "devDependencies": {
45
+ "eslint": "^8.57.0",
46
+ "jest": "^30.2.0",
47
+ "prettier": "^3.2.5"
48
+ },
49
+ "files": [
50
+ "bin/",
51
+ "lib/",
52
+ "middleware/",
53
+ "routes/",
54
+ "server.js",
55
+ "README.md",
56
+ "LICENSE"
57
+ ]
35
58
  }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * HTTP request handler for MacServer
3
+ */
4
+
5
+ const { checkHttpAuth, sendAuthError } = require('../middleware/authMiddleware');
6
+ const { ErrorCodes, createError } = require('../lib/errorCodes');
7
+
8
+ const MAX_HTTP_BODY_SIZE = 64 * 1024; // 64KB
9
+
10
+ /**
11
+ * Create HTTP request handler
12
+ * @param {Object} server - Server instance with apiKey, clients, currentPath, lastHookEvent
13
+ * @param {Function} handleHookEvent - Hook event handler
14
+ * @returns {Function} HTTP request handler
15
+ */
16
+ function createHttpHandler(server, handleHookEvent) {
17
+ return function handleHttpRequest(req, res) {
18
+ const clientIP = req.socket.remoteAddress || 'unknown';
19
+
20
+ // CORS headers — restrict to localhost origins in production
21
+ const origin = req.headers['origin'] || '';
22
+ const allowedOrigins = ['http://localhost', 'http://127.0.0.1', 'https://localhost', 'https://127.0.0.1'];
23
+ const isAllowed = allowedOrigins.some(o => origin.startsWith(o));
24
+ if (isAllowed) {
25
+ res.setHeader('Access-Control-Allow-Origin', origin);
26
+ }
27
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
28
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-API-Key, Authorization');
29
+
30
+ if (req.method === 'OPTIONS') {
31
+ res.writeHead(200);
32
+ res.end();
33
+ return;
34
+ }
35
+
36
+ // POST /hook - Claude Code hook events
37
+ if (req.method === 'POST' && req.url === '/hook') {
38
+ const authResult = checkHttpAuth(req, server.apiKey);
39
+ if (!authResult.authenticated) {
40
+ sendAuthError(res, authResult, clientIP, '/hook');
41
+ return;
42
+ }
43
+
44
+ const bodyChunks = [];
45
+ let bodySize = 0;
46
+ let bodyTooLarge = false;
47
+
48
+ req.on('data', chunk => {
49
+ if (bodyTooLarge) return;
50
+ bodySize += chunk.length;
51
+ if (bodySize > MAX_HTTP_BODY_SIZE) {
52
+ bodyTooLarge = true;
53
+ res.writeHead(413, { 'Content-Type': 'application/json' });
54
+ res.end(JSON.stringify(createError(
55
+ ErrorCodes.INVALID_REQUEST,
56
+ 'Payload too large'
57
+ )));
58
+ req.destroy();
59
+ return;
60
+ }
61
+ bodyChunks.push(chunk);
62
+ });
63
+
64
+ req.on('end', () => {
65
+ if (bodyTooLarge) return;
66
+ try {
67
+ const rawBody = Buffer.concat(bodyChunks).toString('utf8');
68
+ const hookData = JSON.parse(rawBody);
69
+ handleHookEvent(hookData);
70
+ res.writeHead(200, { 'Content-Type': 'application/json' });
71
+ res.end(JSON.stringify({ success: true }));
72
+ } catch (error) {
73
+ console.error('Hook parse error:', error.message);
74
+ res.writeHead(400, { 'Content-Type': 'application/json' });
75
+ res.end(JSON.stringify(createError(
76
+ ErrorCodes.INVALID_REQUEST,
77
+ 'Invalid JSON'
78
+ )));
79
+ }
80
+ });
81
+ return;
82
+ }
83
+
84
+ // GET /status - Server status
85
+ if (req.method === 'GET' && req.url === '/status') {
86
+ const authResult = checkHttpAuth(req, server.apiKey);
87
+ if (!authResult.authenticated) {
88
+ sendAuthError(res, authResult, clientIP, '/status');
89
+ return;
90
+ }
91
+
92
+ res.writeHead(200, { 'Content-Type': 'application/json' });
93
+ res.end(JSON.stringify({
94
+ status: 'running',
95
+ clients: server.clients.size,
96
+ externalClients: server.externalClients ? server.externalClients.size : server.clients.size,
97
+ path: server.currentPath,
98
+ lastHookEvent: server.lastHookEvent ? { event: server.lastHookEvent.event, timestamp: server.lastHookEvent.timestamp } : null
99
+ }));
100
+ return;
101
+ }
102
+
103
+ // 404 for unknown routes
104
+ res.writeHead(404, { 'Content-Type': 'application/json' });
105
+ res.end(JSON.stringify({ error: 'Not Found' }));
106
+ };
107
+ }
108
+
109
+ module.exports = { createHttpHandler };