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.
- package/README.md +9 -1
- package/bin/tactic-remote-server.js +636 -0
- package/lib/authChallengeManager.js +134 -0
- package/lib/bonjourPublisher.js +68 -0
- package/lib/errorCodes.js +127 -0
- package/lib/execSafe.js +218 -0
- package/lib/fileService.js +177 -0
- package/lib/hookInstaller.js +239 -0
- package/lib/outputParser.js +106 -0
- package/lib/rateLimiter.js +111 -0
- package/lib/tmuxManager.js +671 -0
- package/lib/uploadService.js +366 -0
- package/lib/validators.js +350 -0
- package/middleware/authMiddleware.js +152 -0
- package/package.json +32 -9
- package/routes/httpHandler.js +109 -0
- package/routes/wsHandler.js +1040 -0
- package/server.js +321 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File system service for MacServer
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { execFileSync } = require('child_process');
|
|
8
|
+
const { validatePath } = require('./validators');
|
|
9
|
+
const { ErrorCodes, createError } = require('./errorCodes');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Change working directory
|
|
13
|
+
* @param {string} newPath - Path to change to
|
|
14
|
+
* @param {string} allowedBasePath - Base path restriction
|
|
15
|
+
* @param {string} currentPath - Current client path for resolving relative paths
|
|
16
|
+
* @returns {Object} Result with success status and path or error
|
|
17
|
+
*/
|
|
18
|
+
function changePath(newPath, allowedBasePath, currentPath) {
|
|
19
|
+
const validation = validatePath(newPath, { allowedBasePath, currentPath });
|
|
20
|
+
|
|
21
|
+
if (!validation.valid) {
|
|
22
|
+
return {
|
|
23
|
+
success: false,
|
|
24
|
+
error: createError(ErrorCodes.PATH_INVALID, validation.error)
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const expandedPath = validation.path;
|
|
29
|
+
|
|
30
|
+
if (!fs.existsSync(expandedPath)) {
|
|
31
|
+
return {
|
|
32
|
+
success: false,
|
|
33
|
+
error: createError(ErrorCodes.PATH_NOT_FOUND, `Path does not exist: ${newPath}`)
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (!fs.statSync(expandedPath).isDirectory()) {
|
|
38
|
+
return {
|
|
39
|
+
success: false,
|
|
40
|
+
error: createError(ErrorCodes.PATH_INVALID, `Not a directory: ${newPath}`)
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
success: true,
|
|
46
|
+
path: expandedPath
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Create a new folder
|
|
52
|
+
* @param {string} folderPath - Path for new folder
|
|
53
|
+
* @param {string} allowedBasePath - Base path restriction
|
|
54
|
+
* @param {string} currentPath - Current client path for resolving relative paths
|
|
55
|
+
* @returns {Object} Result with success status
|
|
56
|
+
*/
|
|
57
|
+
function createFolder(folderPath, allowedBasePath, currentPath) {
|
|
58
|
+
const validation = validatePath(folderPath, { allowedBasePath, currentPath });
|
|
59
|
+
|
|
60
|
+
if (!validation.valid) {
|
|
61
|
+
return {
|
|
62
|
+
success: false,
|
|
63
|
+
error: createError(ErrorCodes.PATH_INVALID, validation.error)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const expandedPath = validation.path;
|
|
68
|
+
|
|
69
|
+
if (fs.existsSync(expandedPath)) {
|
|
70
|
+
return {
|
|
71
|
+
success: false,
|
|
72
|
+
error: createError(ErrorCodes.PATH_INVALID, `Path already exists: ${folderPath}`)
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
fs.mkdirSync(expandedPath, { recursive: true });
|
|
78
|
+
return {
|
|
79
|
+
success: true,
|
|
80
|
+
path: expandedPath
|
|
81
|
+
};
|
|
82
|
+
} catch (err) {
|
|
83
|
+
return {
|
|
84
|
+
success: false,
|
|
85
|
+
error: createError(ErrorCodes.PATH_ACCESS_DENIED, err.message)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* List directory contents
|
|
92
|
+
* @param {string} dirPath - Directory to list
|
|
93
|
+
* @param {string} allowedBasePath - Base path restriction
|
|
94
|
+
* @param {string} currentPath - Current client path for resolving relative paths
|
|
95
|
+
* @returns {Object} Result with items or error
|
|
96
|
+
*/
|
|
97
|
+
function listDirectory(dirPath, allowedBasePath, currentPath) {
|
|
98
|
+
const validation = validatePath(dirPath, { allowBrowse: true, allowedBasePath, currentPath });
|
|
99
|
+
|
|
100
|
+
if (!validation.valid) {
|
|
101
|
+
return {
|
|
102
|
+
success: false,
|
|
103
|
+
error: createError(ErrorCodes.PATH_INVALID, validation.error)
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const expandedPath = validation.path;
|
|
108
|
+
|
|
109
|
+
if (!fs.existsSync(expandedPath)) {
|
|
110
|
+
return {
|
|
111
|
+
success: false,
|
|
112
|
+
error: createError(ErrorCodes.PATH_NOT_FOUND, `Directory does not exist: ${dirPath}`)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (!fs.statSync(expandedPath).isDirectory()) {
|
|
117
|
+
return {
|
|
118
|
+
success: false,
|
|
119
|
+
error: createError(ErrorCodes.PATH_INVALID, `Not a directory: ${dirPath}`)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
const entries = fs.readdirSync(expandedPath, { withFileTypes: true });
|
|
125
|
+
|
|
126
|
+
const items = entries
|
|
127
|
+
.filter(entry => !entry.name.startsWith('.')) // Hide hidden files
|
|
128
|
+
.map(entry => ({
|
|
129
|
+
name: entry.name,
|
|
130
|
+
isDirectory: entry.isDirectory(),
|
|
131
|
+
path: path.join(expandedPath, entry.name)
|
|
132
|
+
}))
|
|
133
|
+
.sort((a, b) => {
|
|
134
|
+
// Directories first, then alphabetically
|
|
135
|
+
if (a.isDirectory && !b.isDirectory) return -1;
|
|
136
|
+
if (!a.isDirectory && b.isDirectory) return 1;
|
|
137
|
+
return a.name.localeCompare(b.name);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// Enrich items with git status
|
|
141
|
+
const gitStatusMap = {};
|
|
142
|
+
try {
|
|
143
|
+
const output = execFileSync('git', ['-C', expandedPath, 'status', '--short', '--porcelain'], { timeout: 3000, encoding: 'utf-8' });
|
|
144
|
+
for (const line of output.split('\n')) {
|
|
145
|
+
if (line.length < 4) continue;
|
|
146
|
+
const status = line.substring(0, 2).trim();
|
|
147
|
+
let filePath = line.substring(3).trim();
|
|
148
|
+
// For renames: "R old -> new", take the new path
|
|
149
|
+
if (filePath.includes(' -> ')) filePath = filePath.split(' -> ')[1];
|
|
150
|
+
const topLevel = filePath.split('/')[0];
|
|
151
|
+
if (status && topLevel) gitStatusMap[topLevel] = status;
|
|
152
|
+
}
|
|
153
|
+
} catch { /* not a git repo or git not available */ }
|
|
154
|
+
|
|
155
|
+
const enrichedItems = items.map(item => ({
|
|
156
|
+
...item,
|
|
157
|
+
gitStatus: gitStatusMap[item.name] || null
|
|
158
|
+
}));
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
success: true,
|
|
162
|
+
path: expandedPath,
|
|
163
|
+
items: enrichedItems
|
|
164
|
+
};
|
|
165
|
+
} catch (err) {
|
|
166
|
+
return {
|
|
167
|
+
success: false,
|
|
168
|
+
error: createError(ErrorCodes.PATH_ACCESS_DENIED, err.message)
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = {
|
|
174
|
+
changePath,
|
|
175
|
+
createFolder,
|
|
176
|
+
listDirectory
|
|
177
|
+
};
|
|
@@ -0,0 +1,239 @@
|
|
|
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 SCRIPT_FILES = {
|
|
11
|
+
'claude-remote-stop.sh': 'Stop',
|
|
12
|
+
'claude-remote-notification.sh': 'Notification',
|
|
13
|
+
'claude-remote-session-start.sh': 'SessionStart',
|
|
14
|
+
'claude-remote-pre-tool-use.js': 'PreToolUse',
|
|
15
|
+
'claude-remote-post-tool-use.js': 'PostToolUse',
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// ── Hook script content ─────────────────────────────────────────────
|
|
19
|
+
|
|
20
|
+
function bashHookScript(eventName) {
|
|
21
|
+
return `#!/bin/bash
|
|
22
|
+
# Tactic Remote hook — ${eventName} event
|
|
23
|
+
|
|
24
|
+
PORT="\${CLAUDE_REMOTE_PORT:-8765}"
|
|
25
|
+
URL="http://localhost:\${PORT}/hook"
|
|
26
|
+
|
|
27
|
+
json_escape() {
|
|
28
|
+
local value="$1"
|
|
29
|
+
value=\${value//\\/\\\\}
|
|
30
|
+
value=\${value//\"/\\\"}
|
|
31
|
+
value=\${value//$'\\n'/\\n}
|
|
32
|
+
value=\${value//$'\\r'/\\r}
|
|
33
|
+
value=\${value//$'\\t'/\\t}
|
|
34
|
+
printf '%s' "$value"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
TMUX_SESSION=""
|
|
38
|
+
if [ -n "$TMUX" ]; then
|
|
39
|
+
TMUX_SESSION=$(tmux display-message -p '#S' 2>/dev/null || echo "")
|
|
40
|
+
fi
|
|
41
|
+
|
|
42
|
+
PROJECT="$(basename "$PWD")"
|
|
43
|
+
TIMESTAMP=$(date +%s)
|
|
44
|
+
PROJECT_JSON=$(json_escape "$PROJECT")
|
|
45
|
+
TMUX_SESSION_JSON=$(json_escape "$TMUX_SESSION")
|
|
46
|
+
JSON=$(printf '{"event":"%s","project":"%s","tmux_session":"%s","timestamp":%s}' "${eventName}" "$PROJECT_JSON" "$TMUX_SESSION_JSON" "$TIMESTAMP")
|
|
47
|
+
|
|
48
|
+
API_KEY="\${CLAUDE_REMOTE_API_KEY:-}"
|
|
49
|
+
if [ -n "$API_KEY" ]; then
|
|
50
|
+
curl -s -X POST "$URL" \\
|
|
51
|
+
-H "Content-Type: application/json" \\
|
|
52
|
+
-H "X-API-Key: $API_KEY" \\
|
|
53
|
+
-d "$JSON" \\
|
|
54
|
+
> /dev/null 2>&1 &
|
|
55
|
+
else
|
|
56
|
+
curl -s -X POST "$URL" \\
|
|
57
|
+
-H "Content-Type: application/json" \\
|
|
58
|
+
-d "$JSON" \\
|
|
59
|
+
> /dev/null 2>&1 &
|
|
60
|
+
fi
|
|
61
|
+
exit 0
|
|
62
|
+
`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function nodeHookScript() {
|
|
66
|
+
return `#!/usr/bin/env node
|
|
67
|
+
// Tactic Remote hook — tool use event
|
|
68
|
+
const http = require('http');
|
|
69
|
+
let input = '';
|
|
70
|
+
process.stdin.on('data', d => input += d);
|
|
71
|
+
process.stdin.on('end', () => {
|
|
72
|
+
try {
|
|
73
|
+
const data = JSON.parse(input);
|
|
74
|
+
data.project = require('path').basename(process.cwd());
|
|
75
|
+
try { data.tmux_session = require('child_process').execSync("tmux display-message -p '#S'", {timeout:2000}).toString().trim(); } catch(e) {}
|
|
76
|
+
const body = JSON.stringify(data);
|
|
77
|
+
const port = process.env.CLAUDE_REMOTE_PORT || 8765;
|
|
78
|
+
const headers = {'Content-Type':'application/json'};
|
|
79
|
+
if (process.env.CLAUDE_REMOTE_API_KEY) headers['X-API-Key'] = process.env.CLAUDE_REMOTE_API_KEY;
|
|
80
|
+
const req = http.request({hostname:'localhost',port,path:'/hook',method:'POST',headers}, ()=>{});
|
|
81
|
+
req.on('error', ()=>{});
|
|
82
|
+
req.end(body);
|
|
83
|
+
} catch(e) {}
|
|
84
|
+
});
|
|
85
|
+
`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ── Check if hooks are installed ────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
function checkHooksInstalled() {
|
|
91
|
+
// Check if script files exist
|
|
92
|
+
const allFilesExist = Object.keys(SCRIPT_FILES).every(
|
|
93
|
+
f => fs.existsSync(path.join(HOOKS_DIR, f))
|
|
94
|
+
);
|
|
95
|
+
if (!allFilesExist) return false;
|
|
96
|
+
|
|
97
|
+
// Check if registered in settings.json
|
|
98
|
+
if (!fs.existsSync(SETTINGS_PATH)) return false;
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
const settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
|
|
102
|
+
const hooks = settings.hooks;
|
|
103
|
+
if (!hooks) return false;
|
|
104
|
+
|
|
105
|
+
for (const [filename, eventName] of Object.entries(SCRIPT_FILES)) {
|
|
106
|
+
const entries = hooks[eventName];
|
|
107
|
+
if (!Array.isArray(entries)) return false;
|
|
108
|
+
|
|
109
|
+
const scriptPath = path.join(HOOKS_DIR, filename);
|
|
110
|
+
const isNode = filename.endsWith('.js');
|
|
111
|
+
const command = isNode ? `node ${scriptPath}` : scriptPath;
|
|
112
|
+
|
|
113
|
+
const found = entries.some(entry => {
|
|
114
|
+
const hookList = entry.hooks || [];
|
|
115
|
+
return hookList.some(h => h.command === command);
|
|
116
|
+
});
|
|
117
|
+
if (!found) return false;
|
|
118
|
+
}
|
|
119
|
+
return true;
|
|
120
|
+
} catch (_e) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ── Install hooks ───────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
function installHooks() {
|
|
128
|
+
// Ensure hooks directory exists
|
|
129
|
+
fs.mkdirSync(HOOKS_DIR, { recursive: true });
|
|
130
|
+
|
|
131
|
+
// Write script files
|
|
132
|
+
for (const [filename, eventName] of Object.entries(SCRIPT_FILES)) {
|
|
133
|
+
const filepath = path.join(HOOKS_DIR, filename);
|
|
134
|
+
const isNode = filename.endsWith('.js');
|
|
135
|
+
const content = isNode ? nodeHookScript() : bashHookScript(eventName);
|
|
136
|
+
fs.writeFileSync(filepath, content, { mode: 0o755 });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Read or create settings.json
|
|
140
|
+
let settings = {};
|
|
141
|
+
if (fs.existsSync(SETTINGS_PATH)) {
|
|
142
|
+
try {
|
|
143
|
+
settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
|
|
144
|
+
} catch (_e) {
|
|
145
|
+
settings = {};
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (!settings.hooks) {
|
|
150
|
+
settings.hooks = {};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Register each hook (idempotent)
|
|
154
|
+
for (const [filename, eventName] of Object.entries(SCRIPT_FILES)) {
|
|
155
|
+
const scriptPath = path.join(HOOKS_DIR, filename);
|
|
156
|
+
const isNode = filename.endsWith('.js');
|
|
157
|
+
const command = isNode ? `node ${scriptPath}` : scriptPath;
|
|
158
|
+
|
|
159
|
+
if (!settings.hooks[eventName]) {
|
|
160
|
+
settings.hooks[eventName] = [];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const entries = settings.hooks[eventName];
|
|
164
|
+
|
|
165
|
+
// Check if already registered
|
|
166
|
+
const alreadyRegistered = entries.some(entry => {
|
|
167
|
+
const hookList = entry.hooks || [];
|
|
168
|
+
return hookList.some(h => h.command === command);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
if (!alreadyRegistered) {
|
|
172
|
+
entries.push({
|
|
173
|
+
matcher: '*',
|
|
174
|
+
hooks: [{ type: 'command', command }]
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Ensure ~/.claude directory exists
|
|
180
|
+
fs.mkdirSync(path.dirname(SETTINGS_PATH), { recursive: true });
|
|
181
|
+
|
|
182
|
+
// Write settings.json (preserve formatting)
|
|
183
|
+
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + '\n');
|
|
184
|
+
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ── Remove hooks ────────────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
function removeHooks() {
|
|
191
|
+
// Remove script files
|
|
192
|
+
for (const filename of Object.keys(SCRIPT_FILES)) {
|
|
193
|
+
const filepath = path.join(HOOKS_DIR, filename);
|
|
194
|
+
try { fs.unlinkSync(filepath); } catch (_e) { /* ignore */ }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Remove from settings.json
|
|
198
|
+
if (!fs.existsSync(SETTINGS_PATH)) return;
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf-8'));
|
|
202
|
+
if (!settings.hooks) return;
|
|
203
|
+
|
|
204
|
+
const ourScripts = new Set();
|
|
205
|
+
for (const filename of Object.keys(SCRIPT_FILES)) {
|
|
206
|
+
const scriptPath = path.join(HOOKS_DIR, filename);
|
|
207
|
+
ourScripts.add(scriptPath);
|
|
208
|
+
ourScripts.add(`node ${scriptPath}`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
for (const eventName of Object.values(SCRIPT_FILES)) {
|
|
212
|
+
const entries = settings.hooks[eventName];
|
|
213
|
+
if (!Array.isArray(entries)) continue;
|
|
214
|
+
|
|
215
|
+
// Filter out our hooks, keep user's hooks
|
|
216
|
+
settings.hooks[eventName] = entries.filter(entry => {
|
|
217
|
+
const hookList = entry.hooks || [];
|
|
218
|
+
const filtered = hookList.filter(h => !ourScripts.has(h.command));
|
|
219
|
+
if (filtered.length === 0) return false;
|
|
220
|
+
entry.hooks = filtered;
|
|
221
|
+
return true;
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// Remove empty event arrays
|
|
225
|
+
if (settings.hooks[eventName].length === 0) {
|
|
226
|
+
delete settings.hooks[eventName];
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Remove empty hooks object
|
|
231
|
+
if (Object.keys(settings.hooks).length === 0) {
|
|
232
|
+
delete settings.hooks;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + '\n');
|
|
236
|
+
} catch (_e) { /* ignore */ }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
module.exports = { checkHooksInstalled, installHooks, removeHooks };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output parser for Claude Code terminal output
|
|
3
|
+
* Now preserves ANSI codes for iOS client to render colors
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parse and clean Claude Code output
|
|
8
|
+
* Preserves ANSI color codes for client-side rendering
|
|
9
|
+
* @param {string} rawOutput - Raw terminal output with ANSI codes
|
|
10
|
+
* @param {Object} options - Parser options
|
|
11
|
+
* @param {boolean} options.preserveANSI - Whether to keep ANSI codes (default: true)
|
|
12
|
+
* @param {number} options.maxLines - Maximum lines to return (default: 500)
|
|
13
|
+
* @returns {Object} Parsed output with display text
|
|
14
|
+
*/
|
|
15
|
+
function parseClaudeOutput(rawOutput, options = {}) {
|
|
16
|
+
const { preserveANSI = true, maxLines = 5000 } = options;
|
|
17
|
+
|
|
18
|
+
let cleaned = rawOutput;
|
|
19
|
+
|
|
20
|
+
// Remove problematic control sequences but keep color codes
|
|
21
|
+
cleaned = cleaned
|
|
22
|
+
.replace(/\x1b\].*?\x07/g, '') // OSC sequences (terminal title etc)
|
|
23
|
+
.replace(/\x1b\[\?[0-9;]*[a-z]/g, '') // Private mode sequences
|
|
24
|
+
.replace(/\x1b\[[0-9;]*[ABCDEFGJKST]/g, '') // Cursor movement (but not 'm' for colors)
|
|
25
|
+
.replace(/\r/g, ''); // Carriage returns
|
|
26
|
+
|
|
27
|
+
if (!preserveANSI) {
|
|
28
|
+
// Strip all ANSI codes for plain text mode
|
|
29
|
+
cleaned = cleaned
|
|
30
|
+
.replace(/\x1b\[[0-9;]*m/g, '')
|
|
31
|
+
.replace(/[╭╮╰╯│─┬┴┼├┤┌┐└┘║═╔╗╚╝╠╣╦╩╬]/g, ' ');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Normalize excessive newlines
|
|
35
|
+
cleaned = cleaned.replace(/\n{4,}/g, '\n\n\n');
|
|
36
|
+
|
|
37
|
+
// Split and limit lines
|
|
38
|
+
const lines = cleaned.split('\n');
|
|
39
|
+
const displayLines = lines.slice(-maxLines);
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
display: displayLines.join('\n'),
|
|
43
|
+
raw: rawOutput,
|
|
44
|
+
lineCount: displayLines.length,
|
|
45
|
+
hasANSI: /\x1b\[/.test(rawOutput)
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Check if Claude is waiting for user input
|
|
51
|
+
* @param {string} output - Terminal output to check
|
|
52
|
+
* @returns {boolean} Whether Claude is waiting for input
|
|
53
|
+
*/
|
|
54
|
+
function isWaitingForInput(output) {
|
|
55
|
+
return hasClaudeUI(output);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Positively detect Claude CLI's TUI by checking for its unique UI patterns.
|
|
60
|
+
* This avoids false positives from custom shell themes (oh-my-zsh, powerlevel10k,
|
|
61
|
+
* starship, etc.) that use box-drawing chars, icons, or the word "Claude" in paths.
|
|
62
|
+
*
|
|
63
|
+
* Claude Code's TUI uses rounded box-drawing borders (╭╰) that are distinct from
|
|
64
|
+
* the square corners (┌└) common in shell themes. We require at least 2 independent
|
|
65
|
+
* signals to confirm Claude is running.
|
|
66
|
+
*/
|
|
67
|
+
function hasClaudeUI(output) {
|
|
68
|
+
const lines = output.split('\n').slice(-20).join('\n');
|
|
69
|
+
|
|
70
|
+
// Strong signals — each one alone is sufficient
|
|
71
|
+
if (lines.includes('? for shortcuts')) return true;
|
|
72
|
+
// ╭─ and ╰─ together form Claude's characteristic box
|
|
73
|
+
if (lines.includes('╭─') && lines.includes('╰─')) return true;
|
|
74
|
+
|
|
75
|
+
// Medium signals — need at least 2 to confirm
|
|
76
|
+
let score = 0;
|
|
77
|
+
if (lines.includes('╭─')) score++;
|
|
78
|
+
if (lines.includes('╰─')) score++;
|
|
79
|
+
if (/│\s*>/.test(lines)) score++; // bordered input prompt
|
|
80
|
+
if (/claude/i.test(lines) && lines.includes('│')) score++; // "claude" inside bordered UI
|
|
81
|
+
if (lines.includes('●')) score++; // activity indicator
|
|
82
|
+
|
|
83
|
+
return score >= 2;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Check if Claude is currently running
|
|
88
|
+
* @param {string} output - Terminal output to check
|
|
89
|
+
* @returns {boolean} Whether Claude is running
|
|
90
|
+
*/
|
|
91
|
+
function isClaudeRunning(output) {
|
|
92
|
+
if (output.includes('Goodbye!') || output.includes('Session ended')) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
const lastLines = output.split('\n').slice(-10).join('\n');
|
|
96
|
+
if (lastLines.includes('error: An unknown error occurred')) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
return hasClaudeUI(output);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = {
|
|
103
|
+
parseClaudeOutput,
|
|
104
|
+
isWaitingForInput,
|
|
105
|
+
isClaudeRunning
|
|
106
|
+
};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate limiter module
|
|
3
|
+
* Simple in-memory rate limiting for authentication attempts
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
class RateLimiter {
|
|
7
|
+
constructor(options = {}) {
|
|
8
|
+
// Default: 30 failed attempts per minute per IP
|
|
9
|
+
this.windowMs = options.windowMs || 60 * 1000;
|
|
10
|
+
this.maxAttempts = options.maxAttempts || 30;
|
|
11
|
+
this.records = new Map();
|
|
12
|
+
|
|
13
|
+
// Clean up expired records periodically
|
|
14
|
+
// Use the smaller of windowMs or 60 seconds for responsive cleanup
|
|
15
|
+
const cleanupMs = Math.min(this.windowMs, 60 * 1000);
|
|
16
|
+
this.cleanupInterval = setInterval(() => {
|
|
17
|
+
this.cleanup();
|
|
18
|
+
}, cleanupMs);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Check if an IP is rate limited
|
|
23
|
+
* @param {string} ip - Client IP address
|
|
24
|
+
* @returns {boolean} - true if allowed, false if rate limited
|
|
25
|
+
*/
|
|
26
|
+
isAllowed(ip) {
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
const record = this.records.get(ip);
|
|
29
|
+
|
|
30
|
+
if (!record) {
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Reset if window has passed
|
|
35
|
+
if (now > record.resetTime) {
|
|
36
|
+
this.records.delete(ip);
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return record.count < this.maxAttempts;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Record a failed authentication attempt
|
|
45
|
+
* @param {string} ip - Client IP address
|
|
46
|
+
*/
|
|
47
|
+
recordFailure(ip) {
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
let record = this.records.get(ip);
|
|
50
|
+
|
|
51
|
+
if (!record || now > record.resetTime) {
|
|
52
|
+
record = {
|
|
53
|
+
count: 0,
|
|
54
|
+
resetTime: now + this.windowMs
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
record.count++;
|
|
59
|
+
this.records.set(ip, record);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Get remaining attempts for an IP
|
|
64
|
+
* @param {string} ip - Client IP address
|
|
65
|
+
* @returns {number} - Remaining attempts
|
|
66
|
+
*/
|
|
67
|
+
getRemainingAttempts(ip) {
|
|
68
|
+
const record = this.records.get(ip);
|
|
69
|
+
if (!record || Date.now() > record.resetTime) {
|
|
70
|
+
return this.maxAttempts;
|
|
71
|
+
}
|
|
72
|
+
return Math.max(0, this.maxAttempts - record.count);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Get time until reset for an IP (in seconds)
|
|
77
|
+
* @param {string} ip - Client IP address
|
|
78
|
+
* @returns {number} - Seconds until reset, 0 if not limited
|
|
79
|
+
*/
|
|
80
|
+
getResetTime(ip) {
|
|
81
|
+
const record = this.records.get(ip);
|
|
82
|
+
if (!record) {
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
const remaining = record.resetTime - Date.now();
|
|
86
|
+
return remaining > 0 ? Math.ceil(remaining / 1000) : 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Clean up expired records
|
|
91
|
+
*/
|
|
92
|
+
cleanup() {
|
|
93
|
+
const now = Date.now();
|
|
94
|
+
for (const [ip, record] of this.records.entries()) {
|
|
95
|
+
if (now > record.resetTime) {
|
|
96
|
+
this.records.delete(ip);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Stop the cleanup interval (for graceful shutdown)
|
|
103
|
+
*/
|
|
104
|
+
destroy() {
|
|
105
|
+
if (this.cleanupInterval) {
|
|
106
|
+
clearInterval(this.cleanupInterval);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { RateLimiter };
|