tacticremote 1.7.0 → 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/LICENSE +28 -0
- package/README.md +33 -41
- package/bin/tacticremote.js +41 -101
- package/package.json +30 -42
- package/bin/tactic-remote-server.js +0 -636
- package/lib/authChallengeManager.js +0 -1
- package/lib/bonjourPublisher.js +0 -68
- package/lib/claudeSessionManager.js +0 -1
- package/lib/claudeTransport.js +0 -1
- package/lib/errorCodes.js +0 -1
- package/lib/execSafe.js +0 -1
- package/lib/fileService.js +0 -1
- package/lib/hookInstaller.js +0 -253
- package/lib/outputParser.js +0 -1
- package/lib/pushClient.js +0 -1
- package/lib/rateLimiter.js +0 -1
- package/lib/serverIdentity.js +0 -1
- package/lib/streamJsonParser.js +0 -1
- package/lib/tmuxManager.js +0 -1
- package/lib/uploadService.js +0 -1
- package/lib/validators.js +0 -1
- package/middleware/authMiddleware.js +0 -152
- package/routes/httpHandler.js +0 -111
- package/routes/wsHandler.js +0 -1094
- package/server.js +0 -236
- package/shared/server-core/authChallengeManager.js +0 -108
- package/shared/server-core/claudeSessionManager.js +0 -222
- package/shared/server-core/claudeTransport.js +0 -176
- package/shared/server-core/errorCodes.js +0 -91
- package/shared/server-core/execSafe.js +0 -185
- package/shared/server-core/fileService.js +0 -155
- package/shared/server-core/outputParser.js +0 -174
- package/shared/server-core/protocol-manifest.json +0 -59
- package/shared/server-core/protocol-manifest.schema.json +0 -90
- package/shared/server-core/protocolManifest.js +0 -42
- package/shared/server-core/pushClient.js +0 -198
- package/shared/server-core/rateLimiter.js +0 -98
- package/shared/server-core/serverConnectionLifecycle.js +0 -118
- package/shared/server-core/serverHandshake.js +0 -72
- package/shared/server-core/serverIdentity.js +0 -102
- package/shared/server-core/streamJsonParser.js +0 -321
- package/shared/server-core/tmuxManager.js +0 -596
- package/shared/server-core/unixProcessLifecycle.js +0 -96
- package/shared/server-core/unixServerHooks.js +0 -148
- package/shared/server-core/unixWsRuntime.js +0 -412
- package/shared/server-core/uploadService.js +0 -321
- package/shared/server-core/validators.js +0 -274
- package/shared/server-core/windowsServerHooks.js +0 -174
- package/shared/server-core/windowsWsRuntime.js +0 -413
package/lib/bonjourPublisher.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
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 };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/claudeSessionManager');
|
package/lib/claudeTransport.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/claudeTransport');
|
package/lib/errorCodes.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/errorCodes');
|
package/lib/execSafe.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/execSafe');
|
package/lib/fileService.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/fileService');
|
package/lib/hookInstaller.js
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const fs = require('fs');
|
|
4
|
-
const path = require('path');
|
|
5
|
-
const os = require('os');
|
|
6
|
-
|
|
7
|
-
const HOOKS_DIR = path.join(os.homedir(), '.claude', 'hooks');
|
|
8
|
-
const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
|
|
9
|
-
|
|
10
|
-
const HOOK_SCRIPT_VERSION = 2;
|
|
11
|
-
const HOOK_VERSION_TAG = `tactic-hook-version: ${HOOK_SCRIPT_VERSION}`;
|
|
12
|
-
|
|
13
|
-
const SCRIPT_FILES = {
|
|
14
|
-
'claude-remote-stop.sh': 'Stop',
|
|
15
|
-
'claude-remote-notification.sh': 'Notification',
|
|
16
|
-
'claude-remote-session-start.sh': 'SessionStart',
|
|
17
|
-
'claude-remote-pre-tool-use.js': 'PreToolUse',
|
|
18
|
-
'claude-remote-post-tool-use.js': 'PostToolUse',
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
// ── Hook script content ─────────────────────────────────────────────
|
|
22
|
-
|
|
23
|
-
function bashHookScript(eventName) {
|
|
24
|
-
return `#!/bin/bash
|
|
25
|
-
# Tactic Remote hook — ${eventName} event
|
|
26
|
-
# ${HOOK_VERSION_TAG}
|
|
27
|
-
|
|
28
|
-
PORT="\${CLAUDE_REMOTE_PORT:-8765}"
|
|
29
|
-
URL="http://localhost:\${PORT}/hook"
|
|
30
|
-
|
|
31
|
-
json_escape() {
|
|
32
|
-
local value="$1"
|
|
33
|
-
value=\${value//\\/\\\\}
|
|
34
|
-
value=\${value//\"/\\\"}
|
|
35
|
-
value=\${value//$'\\n'/\\n}
|
|
36
|
-
value=\${value//$'\\r'/\\r}
|
|
37
|
-
value=\${value//$'\\t'/\\t}
|
|
38
|
-
printf '%s' "$value"
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
TACTIC_SESSION="\${TACTIC_SESSION_ID:-}"
|
|
42
|
-
|
|
43
|
-
PROJECT="$(basename "$PWD")"
|
|
44
|
-
TIMESTAMP=$(date +%s)
|
|
45
|
-
PROJECT_JSON=$(json_escape "$PROJECT")
|
|
46
|
-
TACTIC_SESSION_JSON=$(json_escape "$TACTIC_SESSION")
|
|
47
|
-
JSON=$(printf '{"event":"%s","project":"%s","tactic_session":"%s","tmux_session":"%s","timestamp":%s}' "${eventName}" "$PROJECT_JSON" "$TACTIC_SESSION_JSON" "$TACTIC_SESSION_JSON" "$TIMESTAMP")
|
|
48
|
-
|
|
49
|
-
API_KEY="\${CLAUDE_REMOTE_API_KEY:-}"
|
|
50
|
-
if [ -n "$API_KEY" ]; then
|
|
51
|
-
curl -s -X POST "$URL" \\
|
|
52
|
-
-H "Content-Type: application/json" \\
|
|
53
|
-
-H "X-API-Key: $API_KEY" \\
|
|
54
|
-
-d "$JSON" \\
|
|
55
|
-
> /dev/null 2>&1 &
|
|
56
|
-
else
|
|
57
|
-
curl -s -X POST "$URL" \\
|
|
58
|
-
-H "Content-Type: application/json" \\
|
|
59
|
-
-d "$JSON" \\
|
|
60
|
-
> /dev/null 2>&1 &
|
|
61
|
-
fi
|
|
62
|
-
exit 0
|
|
63
|
-
`;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function nodeHookScript() {
|
|
67
|
-
return `#!/usr/bin/env node
|
|
68
|
-
// Tactic Remote hook — tool use event
|
|
69
|
-
// ${HOOK_VERSION_TAG}
|
|
70
|
-
const http = require('http');
|
|
71
|
-
let input = '';
|
|
72
|
-
process.stdin.on('data', d => input += d);
|
|
73
|
-
process.stdin.on('end', () => {
|
|
74
|
-
try {
|
|
75
|
-
const data = JSON.parse(input);
|
|
76
|
-
data.project = require('path').basename(process.cwd());
|
|
77
|
-
data.tactic_session = process.env.TACTIC_SESSION_ID || '';
|
|
78
|
-
data.tmux_session = data.tactic_session;
|
|
79
|
-
const body = JSON.stringify(data);
|
|
80
|
-
const port = process.env.CLAUDE_REMOTE_PORT || 8765;
|
|
81
|
-
const headers = {'Content-Type':'application/json'};
|
|
82
|
-
if (process.env.CLAUDE_REMOTE_API_KEY) headers['X-API-Key'] = process.env.CLAUDE_REMOTE_API_KEY;
|
|
83
|
-
const req = http.request({hostname:'localhost',port,path:'/hook',method:'POST',headers}, ()=>{});
|
|
84
|
-
req.on('error', ()=>{});
|
|
85
|
-
req.end(body);
|
|
86
|
-
} catch(e) {}
|
|
87
|
-
});
|
|
88
|
-
`;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// ── Check if hooks are installed ────────────────────────────────────
|
|
92
|
-
|
|
93
|
-
function checkHooksInstalled() {
|
|
94
|
-
// Check if script files exist
|
|
95
|
-
const allFilesExist = Object.keys(SCRIPT_FILES).every(
|
|
96
|
-
f => fs.existsSync(path.join(HOOKS_DIR, f))
|
|
97
|
-
);
|
|
98
|
-
if (!allFilesExist) return false;
|
|
99
|
-
|
|
100
|
-
// Check script version (forces reinstall after upgrade)
|
|
101
|
-
for (const filename of Object.keys(SCRIPT_FILES)) {
|
|
102
|
-
const filepath = path.join(HOOKS_DIR, filename);
|
|
103
|
-
try {
|
|
104
|
-
const content = fs.readFileSync(filepath, 'utf-8');
|
|
105
|
-
if (!content.includes(HOOK_VERSION_TAG)) return false;
|
|
106
|
-
} catch (_e) {
|
|
107
|
-
return false;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// Check if registered in settings.json
|
|
112
|
-
if (!fs.existsSync(SETTINGS_PATH)) return false;
|
|
113
|
-
|
|
114
|
-
try {
|
|
115
|
-
const settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
|
|
116
|
-
const hooks = settings.hooks;
|
|
117
|
-
if (!hooks) return false;
|
|
118
|
-
|
|
119
|
-
for (const [filename, eventName] of Object.entries(SCRIPT_FILES)) {
|
|
120
|
-
const entries = hooks[eventName];
|
|
121
|
-
if (!Array.isArray(entries)) return false;
|
|
122
|
-
|
|
123
|
-
const scriptPath = path.join(HOOKS_DIR, filename);
|
|
124
|
-
const isNode = filename.endsWith('.js');
|
|
125
|
-
const command = isNode ? `node ${scriptPath}` : scriptPath;
|
|
126
|
-
|
|
127
|
-
const found = entries.some(entry => {
|
|
128
|
-
const hookList = entry.hooks || [];
|
|
129
|
-
return hookList.some(h => h.command === command);
|
|
130
|
-
});
|
|
131
|
-
if (!found) return false;
|
|
132
|
-
}
|
|
133
|
-
return true;
|
|
134
|
-
} catch (_e) {
|
|
135
|
-
return false;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// ── Install hooks ───────────────────────────────────────────────────
|
|
140
|
-
|
|
141
|
-
function installHooks() {
|
|
142
|
-
// Ensure hooks directory exists
|
|
143
|
-
fs.mkdirSync(HOOKS_DIR, { recursive: true });
|
|
144
|
-
|
|
145
|
-
// Write script files
|
|
146
|
-
for (const [filename, eventName] of Object.entries(SCRIPT_FILES)) {
|
|
147
|
-
const filepath = path.join(HOOKS_DIR, filename);
|
|
148
|
-
const isNode = filename.endsWith('.js');
|
|
149
|
-
const content = isNode ? nodeHookScript() : bashHookScript(eventName);
|
|
150
|
-
fs.writeFileSync(filepath, content, { mode: 0o755 });
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// Read or create settings.json
|
|
154
|
-
let settings = {};
|
|
155
|
-
if (fs.existsSync(SETTINGS_PATH)) {
|
|
156
|
-
try {
|
|
157
|
-
settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
|
|
158
|
-
} catch (_e) {
|
|
159
|
-
settings = {};
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
if (!settings.hooks) {
|
|
164
|
-
settings.hooks = {};
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
// Register each hook (idempotent)
|
|
168
|
-
for (const [filename, eventName] of Object.entries(SCRIPT_FILES)) {
|
|
169
|
-
const scriptPath = path.join(HOOKS_DIR, filename);
|
|
170
|
-
const isNode = filename.endsWith('.js');
|
|
171
|
-
const command = isNode ? `node ${scriptPath}` : scriptPath;
|
|
172
|
-
|
|
173
|
-
if (!settings.hooks[eventName]) {
|
|
174
|
-
settings.hooks[eventName] = [];
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
const entries = settings.hooks[eventName];
|
|
178
|
-
|
|
179
|
-
// Check if already registered
|
|
180
|
-
const alreadyRegistered = entries.some(entry => {
|
|
181
|
-
const hookList = entry.hooks || [];
|
|
182
|
-
return hookList.some(h => h.command === command);
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
if (!alreadyRegistered) {
|
|
186
|
-
entries.push({
|
|
187
|
-
matcher: '*',
|
|
188
|
-
hooks: [{ type: 'command', command }]
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
// Ensure ~/.claude directory exists
|
|
194
|
-
fs.mkdirSync(path.dirname(SETTINGS_PATH), { recursive: true });
|
|
195
|
-
|
|
196
|
-
// Write settings.json (preserve formatting)
|
|
197
|
-
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + '\n');
|
|
198
|
-
|
|
199
|
-
return true;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// ── Remove hooks ────────────────────────────────────────────────────
|
|
203
|
-
|
|
204
|
-
function removeHooks() {
|
|
205
|
-
// Remove script files
|
|
206
|
-
for (const filename of Object.keys(SCRIPT_FILES)) {
|
|
207
|
-
const filepath = path.join(HOOKS_DIR, filename);
|
|
208
|
-
try { fs.unlinkSync(filepath); } catch (_e) { /* ignore */ }
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
// Remove from settings.json
|
|
212
|
-
if (!fs.existsSync(SETTINGS_PATH)) return;
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
const settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
|
|
216
|
-
if (!settings.hooks) return;
|
|
217
|
-
|
|
218
|
-
const ourScripts = new Set();
|
|
219
|
-
for (const filename of Object.keys(SCRIPT_FILES)) {
|
|
220
|
-
const scriptPath = path.join(HOOKS_DIR, filename);
|
|
221
|
-
ourScripts.add(scriptPath);
|
|
222
|
-
ourScripts.add(`node ${scriptPath}`);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
for (const eventName of Object.values(SCRIPT_FILES)) {
|
|
226
|
-
const entries = settings.hooks[eventName];
|
|
227
|
-
if (!Array.isArray(entries)) continue;
|
|
228
|
-
|
|
229
|
-
// Filter out our hooks, keep user's hooks
|
|
230
|
-
settings.hooks[eventName] = entries.filter(entry => {
|
|
231
|
-
const hookList = entry.hooks || [];
|
|
232
|
-
const filtered = hookList.filter(h => !ourScripts.has(h.command));
|
|
233
|
-
if (filtered.length === 0) return false;
|
|
234
|
-
entry.hooks = filtered;
|
|
235
|
-
return true;
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
// Remove empty event arrays
|
|
239
|
-
if (settings.hooks[eventName].length === 0) {
|
|
240
|
-
delete settings.hooks[eventName];
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// Remove empty hooks object
|
|
245
|
-
if (Object.keys(settings.hooks).length === 0) {
|
|
246
|
-
delete settings.hooks;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + '\n');
|
|
250
|
-
} catch (_e) { /* ignore */ }
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
module.exports = { checkHooksInstalled, installHooks, removeHooks };
|
package/lib/outputParser.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/outputParser');
|
package/lib/pushClient.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/pushClient');
|
package/lib/rateLimiter.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/rateLimiter');
|
package/lib/serverIdentity.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/serverIdentity');
|
package/lib/streamJsonParser.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/streamJsonParser');
|
package/lib/tmuxManager.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/tmuxManager');
|
package/lib/uploadService.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/uploadService');
|
package/lib/validators.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('../shared/server-core/validators');
|
|
@@ -1,152 +0,0 @@
|
|
|
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/routes/httpHandler.js
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
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
|
-
Promise.resolve(handleHookEvent(hookData)).catch(err => {
|
|
70
|
-
console.error('[hook] handler error:', err.message);
|
|
71
|
-
});
|
|
72
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
73
|
-
res.end(JSON.stringify({ success: true }));
|
|
74
|
-
} catch (error) {
|
|
75
|
-
console.error('Hook parse error:', error.message);
|
|
76
|
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
77
|
-
res.end(JSON.stringify(createError(
|
|
78
|
-
ErrorCodes.INVALID_REQUEST,
|
|
79
|
-
'Invalid JSON'
|
|
80
|
-
)));
|
|
81
|
-
}
|
|
82
|
-
});
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// GET /status - Server status
|
|
87
|
-
if (req.method === 'GET' && req.url === '/status') {
|
|
88
|
-
const authResult = checkHttpAuth(req, server.apiKey);
|
|
89
|
-
if (!authResult.authenticated) {
|
|
90
|
-
sendAuthError(res, authResult, clientIP, '/status');
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
95
|
-
res.end(JSON.stringify({
|
|
96
|
-
status: 'running',
|
|
97
|
-
clients: server.clients.size,
|
|
98
|
-
externalClients: server.externalClients ? server.externalClients.size : server.clients.size,
|
|
99
|
-
path: server.currentPath,
|
|
100
|
-
lastHookEvent: server.lastHookEvent ? { event: server.lastHookEvent.event, timestamp: server.lastHookEvent.timestamp } : null
|
|
101
|
-
}));
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// 404 for unknown routes
|
|
106
|
-
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
107
|
-
res.end(JSON.stringify({ error: 'Not Found' }));
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
module.exports = { createHttpHandler };
|