tacticremote 1.6.5 → 1.7.0
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/lib/authChallengeManager.js +1 -134
- package/lib/claudeSessionManager.js +1 -0
- package/lib/claudeTransport.js +1 -0
- package/lib/errorCodes.js +1 -127
- package/lib/execSafe.js +1 -218
- package/lib/fileService.js +1 -177
- package/lib/hookInstaller.js +21 -7
- package/lib/outputParser.js +1 -106
- package/lib/pushClient.js +1 -0
- package/lib/rateLimiter.js +1 -111
- package/lib/serverIdentity.js +1 -0
- package/lib/streamJsonParser.js +1 -0
- package/lib/tmuxManager.js +1 -671
- package/lib/uploadService.js +1 -366
- package/lib/validators.js +1 -350
- package/package.json +2 -1
- package/routes/httpHandler.js +3 -1
- package/routes/wsHandler.js +418 -364
- package/server.js +67 -152
- package/shared/server-core/authChallengeManager.js +108 -0
- package/shared/server-core/claudeSessionManager.js +222 -0
- package/shared/server-core/claudeTransport.js +176 -0
- package/shared/server-core/errorCodes.js +91 -0
- package/shared/server-core/execSafe.js +185 -0
- package/shared/server-core/fileService.js +155 -0
- package/shared/server-core/outputParser.js +174 -0
- package/shared/server-core/protocol-manifest.json +59 -0
- package/shared/server-core/protocol-manifest.schema.json +90 -0
- package/shared/server-core/protocolManifest.js +42 -0
- package/shared/server-core/pushClient.js +198 -0
- package/shared/server-core/rateLimiter.js +98 -0
- package/shared/server-core/serverConnectionLifecycle.js +118 -0
- package/shared/server-core/serverHandshake.js +72 -0
- package/shared/server-core/serverIdentity.js +102 -0
- package/shared/server-core/streamJsonParser.js +321 -0
- package/shared/server-core/tmuxManager.js +596 -0
- package/shared/server-core/unixProcessLifecycle.js +96 -0
- package/shared/server-core/unixServerHooks.js +148 -0
- package/shared/server-core/unixWsRuntime.js +412 -0
- package/shared/server-core/uploadService.js +321 -0
- package/shared/server-core/validators.js +274 -0
- package/shared/server-core/windowsServerHooks.js +174 -0
- package/shared/server-core/windowsWsRuntime.js +413 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File upload service shared across server variants.
|
|
3
|
+
* Handles chunked file uploads from iOS clients via WebSocket.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const crypto = require('crypto');
|
|
9
|
+
const { validatePath } = require('./validators');
|
|
10
|
+
const { ErrorCodes, createError } = require('./errorCodes');
|
|
11
|
+
|
|
12
|
+
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
|
13
|
+
const CHUNK_TIMEOUT_MS = 60000;
|
|
14
|
+
const MAX_FILENAME_LENGTH = 255;
|
|
15
|
+
const MAX_ACTIVE_UPLOADS = 4;
|
|
16
|
+
|
|
17
|
+
const ALLOWED_MIME_TYPES = new Set([
|
|
18
|
+
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
|
|
19
|
+
'image/bmp', 'image/tiff', 'image/heic', 'image/heif',
|
|
20
|
+
'application/pdf',
|
|
21
|
+
'application/msword',
|
|
22
|
+
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
23
|
+
'application/vnd.ms-excel',
|
|
24
|
+
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
25
|
+
'application/vnd.ms-powerpoint',
|
|
26
|
+
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
27
|
+
'text/plain', 'text/html', 'text/css', 'text/javascript', 'text/markdown',
|
|
28
|
+
'text/csv', 'text/xml', 'text/yaml',
|
|
29
|
+
'application/json', 'application/xml', 'application/javascript',
|
|
30
|
+
'application/typescript', 'application/x-yaml',
|
|
31
|
+
'application/zip', 'application/gzip', 'application/x-tar',
|
|
32
|
+
'application/x-7z-compressed',
|
|
33
|
+
'application/octet-stream'
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
const activeUploads = new Map();
|
|
37
|
+
|
|
38
|
+
function sanitizeFilename(filename) {
|
|
39
|
+
if (!filename || typeof filename !== 'string') {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
let clean = filename.replace(/[/\\]/g, '_').replace(/\.\./g, '_');
|
|
43
|
+
clean = clean.replace(/[\x00-\x1f\x7f<>:"|?*]/g, '_');
|
|
44
|
+
clean = clean.replace(/^[\s.]+|[\s.]+$/g, '');
|
|
45
|
+
if (clean.length > MAX_FILENAME_LENGTH) {
|
|
46
|
+
const ext = path.extname(clean);
|
|
47
|
+
const base = path.basename(clean, ext);
|
|
48
|
+
clean = base.substring(0, MAX_FILENAME_LENGTH - ext.length) + ext;
|
|
49
|
+
}
|
|
50
|
+
return clean || null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function resolveFilename(destDir, filename) {
|
|
54
|
+
let candidate = path.join(destDir, filename);
|
|
55
|
+
if (!fs.existsSync(candidate)) {
|
|
56
|
+
return candidate;
|
|
57
|
+
}
|
|
58
|
+
const ext = path.extname(filename);
|
|
59
|
+
const base = path.basename(filename, ext);
|
|
60
|
+
let counter = 1;
|
|
61
|
+
while (fs.existsSync(candidate) && counter < 1000) {
|
|
62
|
+
candidate = path.join(destDir, `${base} (${counter})${ext}`);
|
|
63
|
+
counter++;
|
|
64
|
+
}
|
|
65
|
+
return candidate;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function startUpload(filename, size, mimeType, totalChunks, destPath, allowedBasePath, currentPath) {
|
|
69
|
+
const cleanFilename = sanitizeFilename(filename);
|
|
70
|
+
if (!cleanFilename) {
|
|
71
|
+
return {
|
|
72
|
+
success: false,
|
|
73
|
+
error: createError(ErrorCodes.UPLOAD_INVALID_TYPE, 'Invalid filename')
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (!size || typeof size !== 'number' || size <= 0) {
|
|
78
|
+
return {
|
|
79
|
+
success: false,
|
|
80
|
+
error: createError(ErrorCodes.UPLOAD_TOO_LARGE, 'Invalid file size')
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (size > MAX_FILE_SIZE) {
|
|
84
|
+
return {
|
|
85
|
+
success: false,
|
|
86
|
+
error: createError(
|
|
87
|
+
ErrorCodes.UPLOAD_TOO_LARGE,
|
|
88
|
+
`File too large: ${(size / 1024 / 1024).toFixed(1)}MB exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit`
|
|
89
|
+
)
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (!mimeType || !ALLOWED_MIME_TYPES.has(mimeType)) {
|
|
94
|
+
return {
|
|
95
|
+
success: false,
|
|
96
|
+
error: createError(ErrorCodes.UPLOAD_INVALID_TYPE, `Unsupported file type: ${mimeType}`)
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (!totalChunks || typeof totalChunks !== 'number' || totalChunks <= 0) {
|
|
101
|
+
return {
|
|
102
|
+
success: false,
|
|
103
|
+
error: createError(ErrorCodes.INVALID_REQUEST, 'Invalid chunk count')
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (activeUploads.size >= MAX_ACTIVE_UPLOADS) {
|
|
108
|
+
return {
|
|
109
|
+
success: false,
|
|
110
|
+
error: createError(ErrorCodes.RATE_LIMITED, 'Too many concurrent uploads. Wait for an active upload to finish and try again.')
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const destDir = destPath || currentPath || allowedBasePath;
|
|
115
|
+
const pathValidation = validatePath(destDir, { allowedBasePath, currentPath });
|
|
116
|
+
if (!pathValidation.valid) {
|
|
117
|
+
return {
|
|
118
|
+
success: false,
|
|
119
|
+
error: createError(ErrorCodes.UPLOAD_PATH_DENIED, pathValidation.error)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const resolvedDestDir = pathValidation.path;
|
|
124
|
+
if (!fs.existsSync(resolvedDestDir) || !fs.statSync(resolvedDestDir).isDirectory()) {
|
|
125
|
+
return {
|
|
126
|
+
success: false,
|
|
127
|
+
error: createError(ErrorCodes.UPLOAD_PATH_DENIED, 'Destination directory does not exist')
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const uploadId = crypto.randomUUID();
|
|
132
|
+
const finalPath = resolveFilename(resolvedDestDir, cleanFilename);
|
|
133
|
+
const tempPath = finalPath + '.upload-tmp';
|
|
134
|
+
|
|
135
|
+
try {
|
|
136
|
+
fs.writeFileSync(tempPath, Buffer.alloc(0));
|
|
137
|
+
} catch (err) {
|
|
138
|
+
return {
|
|
139
|
+
success: false,
|
|
140
|
+
error: createError(ErrorCodes.INTERNAL_ERROR, `Failed to create temp file: ${err.message}`)
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
cancelUpload(uploadId);
|
|
146
|
+
}, CHUNK_TIMEOUT_MS);
|
|
147
|
+
|
|
148
|
+
activeUploads.set(uploadId, {
|
|
149
|
+
filename: cleanFilename,
|
|
150
|
+
finalPath,
|
|
151
|
+
tempPath,
|
|
152
|
+
size,
|
|
153
|
+
mimeType,
|
|
154
|
+
totalChunks,
|
|
155
|
+
receivedChunks: new Set(),
|
|
156
|
+
receivedBytes: 0,
|
|
157
|
+
timer,
|
|
158
|
+
createdAt: Date.now()
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
success: true,
|
|
163
|
+
uploadId,
|
|
164
|
+
ready: true
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function receiveChunk(uploadId, chunkIndex, base64Data) {
|
|
169
|
+
const upload = activeUploads.get(uploadId);
|
|
170
|
+
if (!upload) {
|
|
171
|
+
return {
|
|
172
|
+
success: false,
|
|
173
|
+
error: createError(ErrorCodes.UPLOAD_NOT_FOUND, 'Upload not found or expired')
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (typeof chunkIndex !== 'number' || chunkIndex < 0 || chunkIndex >= upload.totalChunks) {
|
|
178
|
+
return {
|
|
179
|
+
success: false,
|
|
180
|
+
error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, `Invalid chunk index: ${chunkIndex}`)
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (upload.receivedChunks.has(chunkIndex)) {
|
|
185
|
+
return {
|
|
186
|
+
success: true,
|
|
187
|
+
chunkIndex,
|
|
188
|
+
receivedBytes: upload.receivedBytes
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (chunkIndex !== upload.receivedChunks.size) {
|
|
193
|
+
return {
|
|
194
|
+
success: false,
|
|
195
|
+
error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, `Expected chunk ${upload.receivedChunks.size}, got ${chunkIndex}`)
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
let buffer;
|
|
200
|
+
try {
|
|
201
|
+
buffer = Buffer.from(base64Data, 'base64');
|
|
202
|
+
} catch (_err) {
|
|
203
|
+
return {
|
|
204
|
+
success: false,
|
|
205
|
+
error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, 'Invalid base64 data')
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
fs.appendFileSync(upload.tempPath, buffer);
|
|
211
|
+
} catch (err) {
|
|
212
|
+
return {
|
|
213
|
+
success: false,
|
|
214
|
+
error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, `Failed to write chunk: ${err.message}`)
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
upload.receivedChunks.add(chunkIndex);
|
|
219
|
+
upload.receivedBytes += buffer.length;
|
|
220
|
+
|
|
221
|
+
clearTimeout(upload.timer);
|
|
222
|
+
upload.timer = setTimeout(() => {
|
|
223
|
+
cancelUpload(uploadId);
|
|
224
|
+
}, CHUNK_TIMEOUT_MS);
|
|
225
|
+
|
|
226
|
+
if (upload.receivedChunks.size === upload.totalChunks) {
|
|
227
|
+
return completeUpload(uploadId);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
success: true,
|
|
232
|
+
chunkIndex,
|
|
233
|
+
receivedBytes: upload.receivedBytes
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function completeUpload(uploadId) {
|
|
238
|
+
const upload = activeUploads.get(uploadId);
|
|
239
|
+
if (!upload) {
|
|
240
|
+
return {
|
|
241
|
+
success: false,
|
|
242
|
+
error: createError(ErrorCodes.UPLOAD_NOT_FOUND, 'Upload not found')
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
clearTimeout(upload.timer);
|
|
247
|
+
|
|
248
|
+
const sizeVariance = Math.abs(upload.receivedBytes - upload.size);
|
|
249
|
+
if (sizeVariance > upload.totalChunks * 3) {
|
|
250
|
+
cleanupTempFile(upload.tempPath);
|
|
251
|
+
activeUploads.delete(uploadId);
|
|
252
|
+
return {
|
|
253
|
+
success: false,
|
|
254
|
+
error: createError(
|
|
255
|
+
ErrorCodes.UPLOAD_CHUNK_ERROR,
|
|
256
|
+
`Size mismatch: expected ${upload.size}, received ${upload.receivedBytes}`
|
|
257
|
+
)
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
fs.renameSync(upload.tempPath, upload.finalPath);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
cleanupTempFile(upload.tempPath);
|
|
265
|
+
activeUploads.delete(uploadId);
|
|
266
|
+
return {
|
|
267
|
+
success: false,
|
|
268
|
+
error: createError(ErrorCodes.INTERNAL_ERROR, `Failed to finalize file: ${err.message}`)
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
activeUploads.delete(uploadId);
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
success: true,
|
|
276
|
+
complete: true,
|
|
277
|
+
filePath: upload.finalPath,
|
|
278
|
+
totalBytes: upload.receivedBytes,
|
|
279
|
+
mimeType: upload.mimeType
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function cancelUpload(uploadId) {
|
|
284
|
+
const upload = activeUploads.get(uploadId);
|
|
285
|
+
if (!upload) {
|
|
286
|
+
return { success: true };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
clearTimeout(upload.timer);
|
|
290
|
+
cleanupTempFile(upload.tempPath);
|
|
291
|
+
activeUploads.delete(uploadId);
|
|
292
|
+
|
|
293
|
+
return { success: true };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function cleanupTempFile(tempPath) {
|
|
297
|
+
try {
|
|
298
|
+
if (fs.existsSync(tempPath)) {
|
|
299
|
+
fs.unlinkSync(tempPath);
|
|
300
|
+
}
|
|
301
|
+
} catch (e) {
|
|
302
|
+
console.error('Failed to cleanup temp file:', e.message);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function getActiveUploadCount() {
|
|
307
|
+
return activeUploads.size;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
module.exports = {
|
|
311
|
+
startUpload,
|
|
312
|
+
receiveChunk,
|
|
313
|
+
cancelUpload,
|
|
314
|
+
completeUpload,
|
|
315
|
+
getActiveUploadCount,
|
|
316
|
+
sanitizeFilename,
|
|
317
|
+
resolveFilename,
|
|
318
|
+
MAX_FILE_SIZE,
|
|
319
|
+
MAX_ACTIVE_UPLOADS,
|
|
320
|
+
ALLOWED_MIME_TYPES
|
|
321
|
+
};
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Input validation module
|
|
3
|
+
* Provides strict validation for all user inputs to prevent injection attacks.
|
|
4
|
+
* This shared variant includes Windows-safe path and key handling while
|
|
5
|
+
* preserving tmux-specific compatibility exports used by Unix backends.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const os = require('os');
|
|
11
|
+
|
|
12
|
+
const SESSION_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
13
|
+
|
|
14
|
+
const KEY_ALLOWLIST = [
|
|
15
|
+
'Enter', 'Escape', 'Tab', 'BTab', 'S-Tab', 'Space',
|
|
16
|
+
'Up', 'Down', 'Left', 'Right',
|
|
17
|
+
'C-c', 'C-d', 'C-u', 'C-z', 'C-m',
|
|
18
|
+
'C-a', 'C-b', 'C-e', 'C-k', 'C-l', 'C-r', 'C-w',
|
|
19
|
+
'F1', 'F2', 'F3', 'F4', 'F5', 'F6',
|
|
20
|
+
'Home', 'End', 'PPage', 'NPage', 'PageUp', 'PageDown',
|
|
21
|
+
'y', 'n', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
const SENSITIVE_DIRS = [
|
|
25
|
+
'.ssh',
|
|
26
|
+
'.gnupg',
|
|
27
|
+
'.aws',
|
|
28
|
+
'.kube',
|
|
29
|
+
'.config\\gcloud',
|
|
30
|
+
'.config/gcloud',
|
|
31
|
+
'AppData\\Roaming\\1Password',
|
|
32
|
+
'AppData\\Local\\1Password',
|
|
33
|
+
'AppData\\Roaming\\Microsoft\\Credentials',
|
|
34
|
+
'AppData\\Roaming\\Microsoft\\Protect',
|
|
35
|
+
'AppData\\Roaming\\gnupg',
|
|
36
|
+
'Library/Keychains',
|
|
37
|
+
'Library/Cookies',
|
|
38
|
+
'Library/Application Support/1Password'
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
function validateSessionName(name) {
|
|
42
|
+
if (!name || typeof name !== 'string') {
|
|
43
|
+
return { valid: false, error: 'Session name is required' };
|
|
44
|
+
}
|
|
45
|
+
if (!SESSION_NAME_RE.test(name)) {
|
|
46
|
+
return { valid: false, error: 'Session name can only contain letters, numbers, underscore and hyphen (max 64 chars)' };
|
|
47
|
+
}
|
|
48
|
+
return { valid: true };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function validateKey(key) {
|
|
52
|
+
if (!key || typeof key !== 'string') {
|
|
53
|
+
return { valid: false, error: 'Key is required' };
|
|
54
|
+
}
|
|
55
|
+
if (KEY_ALLOWLIST.includes(key)) {
|
|
56
|
+
return { valid: true, sanitized: key };
|
|
57
|
+
}
|
|
58
|
+
if (/^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~ ]$/.test(key)) {
|
|
59
|
+
return { valid: true, sanitized: key };
|
|
60
|
+
}
|
|
61
|
+
return { valid: false, error: `Invalid key: ${key}` };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const validateTmuxKey = validateKey;
|
|
65
|
+
|
|
66
|
+
function validateClaudeCommand(cmd) {
|
|
67
|
+
if (!cmd || typeof cmd !== 'string') {
|
|
68
|
+
return { valid: true, sanitized: 'claude' };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const allowedPattern = /^(claude|codex|amp)(\s+--?[a-zA-Z0-9-]+)*$/;
|
|
72
|
+
const trimmed = cmd.trim();
|
|
73
|
+
|
|
74
|
+
if (!allowedPattern.test(trimmed)) {
|
|
75
|
+
return { valid: false, error: 'Invalid agent command format' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { valid: true, sanitized: trimmed };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function getSensitiveDir(resolvedPath) {
|
|
82
|
+
const normalizedPath = resolvedPath.replace(/\\/g, '/');
|
|
83
|
+
const segments = normalizedPath.split('/').filter(Boolean);
|
|
84
|
+
const lowerSegments = segments.map(s => s.toLowerCase());
|
|
85
|
+
|
|
86
|
+
for (const sensitive of SENSITIVE_DIRS) {
|
|
87
|
+
const sensitiveNormalized = sensitive.replace(/\\/g, '/');
|
|
88
|
+
const sensitiveSegments = sensitiveNormalized.toLowerCase().split('/');
|
|
89
|
+
|
|
90
|
+
for (let i = 0; i <= lowerSegments.length - sensitiveSegments.length; i++) {
|
|
91
|
+
let match = true;
|
|
92
|
+
for (let j = 0; j < sensitiveSegments.length; j++) {
|
|
93
|
+
if (lowerSegments[i + j] !== sensitiveSegments[j]) {
|
|
94
|
+
match = false;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (match) return sensitive;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function containsSensitiveDir(resolvedPath) {
|
|
105
|
+
return getSensitiveDir(resolvedPath) !== null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function isPathWithinBase(targetPath, basePath) {
|
|
109
|
+
const relative = path.relative(path.resolve(basePath), path.resolve(targetPath));
|
|
110
|
+
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function validatePath(userPath, options = {}) {
|
|
114
|
+
const {
|
|
115
|
+
allowBrowse = false,
|
|
116
|
+
allowedBasePath = os.homedir(),
|
|
117
|
+
currentPath = allowedBasePath
|
|
118
|
+
} = options;
|
|
119
|
+
|
|
120
|
+
if (!userPath || typeof userPath !== 'string') {
|
|
121
|
+
return { valid: false, error: 'Path is required' };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let cleanPath = userPath.trim();
|
|
125
|
+
const homeDir = os.homedir();
|
|
126
|
+
|
|
127
|
+
if (cleanPath.startsWith('~') && cleanPath.length > 1 && cleanPath[1] === '/') {
|
|
128
|
+
const afterTilde = cleanPath.substring(2);
|
|
129
|
+
if (('/' + afterTilde).startsWith(homeDir)) {
|
|
130
|
+
cleanPath = '/' + afterTilde;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (cleanPath.startsWith('~')) {
|
|
135
|
+
cleanPath = homeDir + cleanPath.substring(1);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const resolvedCurrent = path.resolve(currentPath || allowedBasePath || homeDir);
|
|
139
|
+
const resolvedPath = path.isAbsolute(cleanPath)
|
|
140
|
+
? path.resolve(cleanPath)
|
|
141
|
+
: path.resolve(resolvedCurrent, cleanPath);
|
|
142
|
+
const resolvedBase = path.resolve(allowedBasePath);
|
|
143
|
+
let realHome = homeDir;
|
|
144
|
+
let realBase = resolvedBase;
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
realHome = fs.realpathSync(homeDir);
|
|
148
|
+
} catch {
|
|
149
|
+
// Keep lexical home path if resolution fails
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
realBase = fs.realpathSync(resolvedBase);
|
|
153
|
+
} catch {
|
|
154
|
+
// Keep lexical base path if resolution fails
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let realPath = resolvedPath;
|
|
158
|
+
try {
|
|
159
|
+
realPath = fs.realpathSync(resolvedPath);
|
|
160
|
+
} catch {
|
|
161
|
+
try {
|
|
162
|
+
realPath = path.join(fs.realpathSync(path.dirname(resolvedPath)), path.basename(resolvedPath));
|
|
163
|
+
} catch {
|
|
164
|
+
// Keep lexical resolution for non-existent paths
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const matchedSensitiveDir = getSensitiveDir(realPath);
|
|
169
|
+
if (matchedSensitiveDir) {
|
|
170
|
+
return {
|
|
171
|
+
valid: false,
|
|
172
|
+
error: 'Access denied: sensitive directory',
|
|
173
|
+
requiresAuth: true,
|
|
174
|
+
sensitiveDir: matchedSensitiveDir
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (allowBrowse) {
|
|
179
|
+
if (!isPathWithinBase(realPath, realHome)) {
|
|
180
|
+
return {
|
|
181
|
+
valid: false,
|
|
182
|
+
error: 'Access denied: cannot browse outside home directory'
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
return { valid: true, path: realPath };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (!isPathWithinBase(realPath, realBase)) {
|
|
189
|
+
return {
|
|
190
|
+
valid: false,
|
|
191
|
+
error: `Access denied: path outside allowed directory (${allowedBasePath})`
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return { valid: true, path: realPath };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function escapeForShell(content) {
|
|
199
|
+
if (!content || typeof content !== 'string') return '';
|
|
200
|
+
return content.replace(/\r\n?/g, '\n');
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const escapeForTmux = escapeForShell;
|
|
204
|
+
|
|
205
|
+
function validateLineCount(lines) {
|
|
206
|
+
const num = parseInt(lines, 10);
|
|
207
|
+
if (isNaN(num) || num < 1) {
|
|
208
|
+
return { valid: true, sanitized: 500 };
|
|
209
|
+
}
|
|
210
|
+
return { valid: true, sanitized: Math.min(num, 10000) };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function validateFilename(name) {
|
|
214
|
+
if (!name || typeof name !== 'string') {
|
|
215
|
+
return { valid: false, error: 'Filename is required' };
|
|
216
|
+
}
|
|
217
|
+
if (name.length > 255) {
|
|
218
|
+
return { valid: false, error: 'Filename too long (max 255 characters)' };
|
|
219
|
+
}
|
|
220
|
+
if (/\.\./.test(name) || /[/\\]/.test(name)) {
|
|
221
|
+
return { valid: false, error: 'Filename contains invalid characters' };
|
|
222
|
+
}
|
|
223
|
+
if (/[\x00-\x1f\x7f]/.test(name)) {
|
|
224
|
+
return { valid: false, error: 'Filename contains control characters' };
|
|
225
|
+
}
|
|
226
|
+
return { valid: true };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function validateUploadSize(size, maxSize = 50 * 1024 * 1024) {
|
|
230
|
+
if (typeof size !== 'number' || size <= 0) {
|
|
231
|
+
return { valid: false, error: 'Invalid file size' };
|
|
232
|
+
}
|
|
233
|
+
if (size > maxSize) {
|
|
234
|
+
return { valid: false, error: `File too large: ${(size / 1024 / 1024).toFixed(1)}MB exceeds ${(maxSize / 1024 / 1024)}MB limit` };
|
|
235
|
+
}
|
|
236
|
+
return { valid: true };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function validateMimeType(mime) {
|
|
240
|
+
if (!mime || typeof mime !== 'string') {
|
|
241
|
+
return { valid: false, error: 'MIME type is required' };
|
|
242
|
+
}
|
|
243
|
+
const allowedPrefixes = ['image/', 'text/', 'application/pdf', 'application/json',
|
|
244
|
+
'application/xml', 'application/zip', 'application/gzip', 'application/javascript',
|
|
245
|
+
'application/typescript', 'application/x-yaml', 'application/x-tar',
|
|
246
|
+
'application/x-7z-compressed', 'application/octet-stream',
|
|
247
|
+
'application/msword', 'application/vnd.openxmlformats', 'application/vnd.ms-'];
|
|
248
|
+
const isAllowed = allowedPrefixes.some(prefix => mime.startsWith(prefix));
|
|
249
|
+
if (!isAllowed) {
|
|
250
|
+
return { valid: false, error: `Unsupported file type: ${mime}` };
|
|
251
|
+
}
|
|
252
|
+
return { valid: true };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
module.exports = {
|
|
256
|
+
validateSessionName,
|
|
257
|
+
validateKey,
|
|
258
|
+
validateTmuxKey,
|
|
259
|
+
validateClaudeCommand,
|
|
260
|
+
validatePath,
|
|
261
|
+
escapeForShell,
|
|
262
|
+
escapeForTmux,
|
|
263
|
+
validateLineCount,
|
|
264
|
+
getSensitiveDir,
|
|
265
|
+
containsSensitiveDir,
|
|
266
|
+
isPathWithinBase,
|
|
267
|
+
validateFilename,
|
|
268
|
+
validateUploadSize,
|
|
269
|
+
validateMimeType,
|
|
270
|
+
SESSION_NAME_RE,
|
|
271
|
+
KEY_ALLOWLIST,
|
|
272
|
+
TMUX_KEY_ALLOWLIST: KEY_ALLOWLIST,
|
|
273
|
+
SENSITIVE_DIRS
|
|
274
|
+
};
|