tacticremote 1.6.6 → 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.
@@ -1,366 +0,0 @@
1
- /**
2
- * File upload service for MacServer
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; // 50MB
13
- const CHUNK_TIMEOUT_MS = 60000; // 60 seconds without a chunk → auto-cancel
14
- const MAX_FILENAME_LENGTH = 255;
15
- const MAX_ACTIVE_UPLOADS = 4;
16
-
17
- const ALLOWED_MIME_TYPES = new Set([
18
- // Images
19
- 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
20
- 'image/bmp', 'image/tiff', 'image/heic', 'image/heif',
21
- // Documents
22
- 'application/pdf',
23
- 'application/msword',
24
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
25
- 'application/vnd.ms-excel',
26
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
27
- 'application/vnd.ms-powerpoint',
28
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
29
- // Text & Code
30
- 'text/plain', 'text/html', 'text/css', 'text/javascript', 'text/markdown',
31
- 'text/csv', 'text/xml', 'text/yaml',
32
- 'application/json', 'application/xml', 'application/javascript',
33
- 'application/typescript', 'application/x-yaml',
34
- // Archives
35
- 'application/zip', 'application/gzip', 'application/x-tar',
36
- 'application/x-7z-compressed',
37
- // Other
38
- 'application/octet-stream'
39
- ]);
40
-
41
- // Active uploads: uploadId → { metadata, tempPath, writeStream, receivedChunks, receivedBytes, timer }
42
- const activeUploads = new Map();
43
-
44
- /**
45
- * Sanitize filename — remove path traversal, special chars, limit length
46
- */
47
- function sanitizeFilename(filename) {
48
- if (!filename || typeof filename !== 'string') {
49
- return null;
50
- }
51
- // Remove path separators and traversal
52
- let clean = filename.replace(/[/\\]/g, '_').replace(/\.\./g, '_');
53
- // Remove control characters and problematic chars
54
- clean = clean.replace(/[\x00-\x1f\x7f<>:"|?*]/g, '_');
55
- // Trim whitespace and dots from edges
56
- clean = clean.replace(/^[\s.]+|[\s.]+$/g, '');
57
- // Limit length
58
- if (clean.length > MAX_FILENAME_LENGTH) {
59
- const ext = path.extname(clean);
60
- const base = path.basename(clean, ext);
61
- clean = base.substring(0, MAX_FILENAME_LENGTH - ext.length) + ext;
62
- }
63
- return clean || null;
64
- }
65
-
66
- /**
67
- * Generate a unique filename if a file with the same name already exists
68
- */
69
- function resolveFilename(destDir, filename) {
70
- let candidate = path.join(destDir, filename);
71
- if (!fs.existsSync(candidate)) {
72
- return candidate;
73
- }
74
- const ext = path.extname(filename);
75
- const base = path.basename(filename, ext);
76
- let counter = 1;
77
- while (fs.existsSync(candidate) && counter < 1000) {
78
- candidate = path.join(destDir, `${base} (${counter})${ext}`);
79
- counter++;
80
- }
81
- return candidate;
82
- }
83
-
84
- /**
85
- * Start a new upload
86
- */
87
- function startUpload(filename, size, mimeType, totalChunks, destPath, allowedBasePath, currentPath) {
88
- // Validate filename
89
- const cleanFilename = sanitizeFilename(filename);
90
- if (!cleanFilename) {
91
- return {
92
- success: false,
93
- error: createError(ErrorCodes.UPLOAD_INVALID_TYPE, 'Invalid filename')
94
- };
95
- }
96
-
97
- // Validate size
98
- if (!size || typeof size !== 'number' || size <= 0) {
99
- return {
100
- success: false,
101
- error: createError(ErrorCodes.UPLOAD_TOO_LARGE, 'Invalid file size')
102
- };
103
- }
104
- if (size > MAX_FILE_SIZE) {
105
- return {
106
- success: false,
107
- error: createError(ErrorCodes.UPLOAD_TOO_LARGE,
108
- `File too large: ${(size / 1024 / 1024).toFixed(1)}MB exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit`)
109
- };
110
- }
111
-
112
- // Validate MIME type
113
- if (!mimeType || !ALLOWED_MIME_TYPES.has(mimeType)) {
114
- return {
115
- success: false,
116
- error: createError(ErrorCodes.UPLOAD_INVALID_TYPE, `Unsupported file type: ${mimeType}`)
117
- };
118
- }
119
-
120
- // Validate totalChunks
121
- if (!totalChunks || typeof totalChunks !== 'number' || totalChunks <= 0) {
122
- return {
123
- success: false,
124
- error: createError(ErrorCodes.INVALID_REQUEST, 'Invalid chunk count')
125
- };
126
- }
127
-
128
- if (activeUploads.size >= MAX_ACTIVE_UPLOADS) {
129
- return {
130
- success: false,
131
- error: createError(ErrorCodes.RATE_LIMITED, 'Too many concurrent uploads. Wait for an active upload to finish and try again.')
132
- };
133
- }
134
-
135
- // Resolve destination directory
136
- const destDir = destPath || currentPath || allowedBasePath;
137
- const pathValidation = validatePath(destDir, { allowedBasePath, currentPath });
138
- if (!pathValidation.valid) {
139
- return {
140
- success: false,
141
- error: createError(ErrorCodes.UPLOAD_PATH_DENIED, pathValidation.error)
142
- };
143
- }
144
-
145
- const resolvedDestDir = pathValidation.path;
146
- if (!fs.existsSync(resolvedDestDir) || !fs.statSync(resolvedDestDir).isDirectory()) {
147
- return {
148
- success: false,
149
- error: createError(ErrorCodes.UPLOAD_PATH_DENIED, 'Destination directory does not exist')
150
- };
151
- }
152
-
153
- // Generate upload ID and temp file
154
- const uploadId = crypto.randomUUID();
155
- const finalPath = resolveFilename(resolvedDestDir, cleanFilename);
156
- const tempPath = finalPath + '.upload-tmp';
157
-
158
- try {
159
- // Pre-allocate by creating an empty file
160
- fs.writeFileSync(tempPath, Buffer.alloc(0));
161
- } catch (err) {
162
- return {
163
- success: false,
164
- error: createError(ErrorCodes.INTERNAL_ERROR, `Failed to create temp file: ${err.message}`)
165
- };
166
- }
167
-
168
- // Set up timeout timer
169
- const timer = setTimeout(() => {
170
- cancelUpload(uploadId);
171
- }, CHUNK_TIMEOUT_MS);
172
-
173
- activeUploads.set(uploadId, {
174
- filename: cleanFilename,
175
- finalPath,
176
- tempPath,
177
- size,
178
- mimeType,
179
- totalChunks,
180
- receivedChunks: new Set(),
181
- receivedBytes: 0,
182
- timer,
183
- createdAt: Date.now()
184
- });
185
-
186
- return {
187
- success: true,
188
- uploadId,
189
- ready: true
190
- };
191
- }
192
-
193
- /**
194
- * Receive a chunk of data
195
- */
196
- function receiveChunk(uploadId, chunkIndex, base64Data) {
197
- const upload = activeUploads.get(uploadId);
198
- if (!upload) {
199
- return {
200
- success: false,
201
- error: createError(ErrorCodes.UPLOAD_NOT_FOUND, 'Upload not found or expired')
202
- };
203
- }
204
-
205
- if (typeof chunkIndex !== 'number' || chunkIndex < 0 || chunkIndex >= upload.totalChunks) {
206
- return {
207
- success: false,
208
- error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, `Invalid chunk index: ${chunkIndex}`)
209
- };
210
- }
211
-
212
- if (upload.receivedChunks.has(chunkIndex)) {
213
- // Duplicate chunk — idempotent, just ack
214
- return {
215
- success: true,
216
- chunkIndex,
217
- receivedBytes: upload.receivedBytes
218
- };
219
- }
220
-
221
- // Enforce strict sequential order (WebSocket guarantees order, but defend against bugs)
222
- if (chunkIndex !== upload.receivedChunks.size) {
223
- return {
224
- success: false,
225
- error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, `Expected chunk ${upload.receivedChunks.size}, got ${chunkIndex}`)
226
- };
227
- }
228
-
229
- // Decode base64
230
- let buffer;
231
- try {
232
- buffer = Buffer.from(base64Data, 'base64');
233
- } catch (err) {
234
- return {
235
- success: false,
236
- error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, 'Invalid base64 data')
237
- };
238
- }
239
-
240
- // Write chunk at correct offset
241
- // For simplicity, we append sequentially and track order
242
- try {
243
- fs.appendFileSync(upload.tempPath, buffer);
244
- } catch (err) {
245
- return {
246
- success: false,
247
- error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR, `Failed to write chunk: ${err.message}`)
248
- };
249
- }
250
-
251
- upload.receivedChunks.add(chunkIndex);
252
- upload.receivedBytes += buffer.length;
253
-
254
- // Reset timeout
255
- clearTimeout(upload.timer);
256
- upload.timer = setTimeout(() => {
257
- cancelUpload(uploadId);
258
- }, CHUNK_TIMEOUT_MS);
259
-
260
- // Check if upload is complete
261
- if (upload.receivedChunks.size === upload.totalChunks) {
262
- return completeUpload(uploadId);
263
- }
264
-
265
- return {
266
- success: true,
267
- chunkIndex,
268
- receivedBytes: upload.receivedBytes
269
- };
270
- }
271
-
272
- /**
273
- * Complete an upload — verify and move temp file to final location
274
- */
275
- function completeUpload(uploadId) {
276
- const upload = activeUploads.get(uploadId);
277
- if (!upload) {
278
- return {
279
- success: false,
280
- error: createError(ErrorCodes.UPLOAD_NOT_FOUND, 'Upload not found')
281
- };
282
- }
283
-
284
- clearTimeout(upload.timer);
285
-
286
- // Verify size (allow small variance for base64 padding)
287
- const sizeVariance = Math.abs(upload.receivedBytes - upload.size);
288
- if (sizeVariance > upload.totalChunks * 3) {
289
- // More than 3 bytes per chunk variance (base64 padding) is suspicious
290
- cleanupTempFile(upload.tempPath);
291
- activeUploads.delete(uploadId);
292
- return {
293
- success: false,
294
- error: createError(ErrorCodes.UPLOAD_CHUNK_ERROR,
295
- `Size mismatch: expected ${upload.size}, received ${upload.receivedBytes}`)
296
- };
297
- }
298
-
299
- // Move temp file to final path
300
- try {
301
- fs.renameSync(upload.tempPath, upload.finalPath);
302
- } catch (err) {
303
- cleanupTempFile(upload.tempPath);
304
- activeUploads.delete(uploadId);
305
- return {
306
- success: false,
307
- error: createError(ErrorCodes.INTERNAL_ERROR, `Failed to finalize file: ${err.message}`)
308
- };
309
- }
310
-
311
- activeUploads.delete(uploadId);
312
-
313
- return {
314
- success: true,
315
- complete: true,
316
- filePath: upload.finalPath,
317
- totalBytes: upload.receivedBytes,
318
- mimeType: upload.mimeType
319
- };
320
- }
321
-
322
- /**
323
- * Cancel an upload and clean up
324
- */
325
- function cancelUpload(uploadId) {
326
- const upload = activeUploads.get(uploadId);
327
- if (!upload) {
328
- return { success: true }; // Already gone
329
- }
330
-
331
- clearTimeout(upload.timer);
332
- cleanupTempFile(upload.tempPath);
333
- activeUploads.delete(uploadId);
334
-
335
- return { success: true };
336
- }
337
-
338
- function cleanupTempFile(tempPath) {
339
- try {
340
- if (fs.existsSync(tempPath)) {
341
- fs.unlinkSync(tempPath);
342
- }
343
- } catch (e) {
344
- console.error('Failed to cleanup temp file:', e.message);
345
- }
346
- }
347
-
348
- /**
349
- * Get count of active uploads (for monitoring)
350
- */
351
- function getActiveUploadCount() {
352
- return activeUploads.size;
353
- }
354
-
355
- module.exports = {
356
- startUpload,
357
- receiveChunk,
358
- cancelUpload,
359
- completeUpload,
360
- getActiveUploadCount,
361
- sanitizeFilename,
362
- resolveFilename,
363
- MAX_FILE_SIZE,
364
- MAX_ACTIVE_UPLOADS,
365
- ALLOWED_MIME_TYPES
366
- };
package/lib/validators.js DELETED
@@ -1,350 +0,0 @@
1
- /**
2
- * Input validation module
3
- * Provides strict validation for all user inputs to prevent injection attacks
4
- */
5
-
6
- const path = require('path');
7
- const fs = require('fs');
8
- const os = require('os');
9
-
10
- // Session name: alphanumeric, underscore, hyphen only, max 64 chars
11
- const SESSION_NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
12
-
13
- // Allowed tmux keys whitelist
14
- const TMUX_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
- // Sensitive directories that should never be accessed
25
- const SENSITIVE_DIRS = [
26
- '.ssh',
27
- '.gnupg',
28
- '.aws',
29
- '.kube',
30
- '.config/gcloud',
31
- 'Library/Keychains',
32
- 'Library/Cookies',
33
- 'Library/Application Support/1Password'
34
- ];
35
-
36
- /**
37
- * Validate session name
38
- * @param {string} name - Session name to validate
39
- * @returns {{ valid: boolean, error?: string }}
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
- /**
52
- * Validate tmux key
53
- * @param {string} key - Key to validate
54
- * @returns {{ valid: boolean, error?: string, sanitized?: string }}
55
- */
56
- function validateTmuxKey(key) {
57
- if (!key || typeof key !== 'string') {
58
- return { valid: false, error: 'Key is required' };
59
- }
60
-
61
- // Check whitelist first
62
- if (TMUX_KEY_ALLOWLIST.includes(key)) {
63
- return { valid: true, sanitized: key };
64
- }
65
-
66
- // Allow single printable ASCII characters (for typing)
67
- if (/^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~ ]$/.test(key)) {
68
- return { valid: true, sanitized: key };
69
- }
70
-
71
- return { valid: false, error: `Invalid key: ${key}` };
72
- }
73
-
74
- /**
75
- * Validate Claude command
76
- * @param {string} cmd - Command to validate
77
- * @returns {{ valid: boolean, error?: string, sanitized?: string }}
78
- */
79
- function validateClaudeCommand(cmd) {
80
- if (!cmd || typeof cmd !== 'string') {
81
- return { valid: true, sanitized: 'claude' }; // default
82
- }
83
-
84
- // Only allow claude command with optional flags
85
- // Pattern: claude followed by optional flags like --dangerously-skip-permissions
86
- const allowedPattern = /^(claude|codex)(\s+--?[a-zA-Z0-9-]+)*$/;
87
- const trimmed = cmd.trim();
88
-
89
- if (!allowedPattern.test(trimmed)) {
90
- return { valid: false, error: 'Invalid claude command format' };
91
- }
92
-
93
- return { valid: true, sanitized: trimmed };
94
- }
95
-
96
- /**
97
- * Get the matching sensitive directory entry for a path, or null
98
- * @param {string} resolvedPath - Resolved absolute path
99
- * @returns {string|null} The matched SENSITIVE_DIRS entry, or null
100
- */
101
- function getSensitiveDir(resolvedPath) {
102
- const segments = resolvedPath.split(path.sep).filter(Boolean);
103
- const lowerSegments = segments.map(s => s.toLowerCase());
104
-
105
- for (const sensitive of SENSITIVE_DIRS) {
106
- const sensitiveSegments = sensitive.toLowerCase().split('/');
107
-
108
- for (let i = 0; i <= lowerSegments.length - sensitiveSegments.length; i++) {
109
- let match = true;
110
- for (let j = 0; j < sensitiveSegments.length; j++) {
111
- if (lowerSegments[i + j] !== sensitiveSegments[j]) {
112
- match = false;
113
- break;
114
- }
115
- }
116
- if (match) {
117
- return sensitive;
118
- }
119
- }
120
- }
121
- return null;
122
- }
123
-
124
- /**
125
- * Check if path contains sensitive directories
126
- * @param {string} resolvedPath - Resolved absolute path
127
- * @returns {boolean}
128
- */
129
- function containsSensitiveDir(resolvedPath) {
130
- return getSensitiveDir(resolvedPath) !== null;
131
- }
132
-
133
- /**
134
- * Check whether a target path is inside a base path (or equal to it)
135
- * using normalized relative path checks.
136
- * @param {string} targetPath
137
- * @param {string} basePath
138
- * @returns {boolean}
139
- */
140
- function isPathWithinBase(targetPath, basePath) {
141
- const relative = path.relative(path.resolve(basePath), path.resolve(targetPath));
142
- return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
143
- }
144
-
145
- /**
146
- * Validate file system path
147
- * @param {string} userPath - User-provided path
148
- * @param {object} options - Validation options
149
- * @param {boolean} options.allowBrowse - Allow browsing home directory
150
- * @param {string} options.allowedBasePath - Allowed base path for write operations
151
- * @param {string} options.currentPath - Current client path for resolving relative input paths
152
- * @returns {{ valid: boolean, error?: string, path?: string }}
153
- */
154
- function validatePath(userPath, options = {}) {
155
- const {
156
- allowBrowse = false,
157
- allowedBasePath = os.homedir(),
158
- currentPath = allowedBasePath
159
- } = options;
160
-
161
- if (!userPath || typeof userPath !== 'string') {
162
- return { valid: false, error: 'Path is required' };
163
- }
164
-
165
- // Normalize path: strip leading ~ from absolute paths
166
- let cleanPath = userPath.trim();
167
- const homeDir = os.homedir();
168
-
169
- // Fix malformed "~/Users/yi/..." → "/Users/yi/..." (just remove the ~, keep the /)
170
- if (cleanPath.startsWith('~') && cleanPath.length > 1 && cleanPath[1] === '/') {
171
- const afterTilde = cleanPath.substring(2); // strip "~/"
172
- // If the remainder starts with an absolute-looking segment that matches homedir
173
- if (('/' + afterTilde).startsWith(homeDir)) {
174
- cleanPath = '/' + afterTilde;
175
- }
176
- }
177
-
178
- // Expand ~ or ~/relative to home directory
179
- const expandedPath = cleanPath.startsWith('~')
180
- ? homeDir + cleanPath.substring(1) // ~/foo → /Users/yi/foo, ~ → /Users/yi
181
- : cleanPath;
182
- const resolvedCurrent = path.resolve(currentPath || allowedBasePath || homeDir);
183
- const resolvedPath = path.isAbsolute(expandedPath)
184
- ? path.resolve(expandedPath)
185
- : path.resolve(resolvedCurrent, expandedPath);
186
- const resolvedBase = path.resolve(allowedBasePath);
187
- let realHome = homeDir;
188
- let realBase = resolvedBase;
189
-
190
- try {
191
- realHome = fs.realpathSync(homeDir);
192
- } catch {
193
- // Keep lexical home path if resolution fails
194
- }
195
- try {
196
- realBase = fs.realpathSync(resolvedBase);
197
- } catch {
198
- // Keep lexical base path if resolution fails
199
- }
200
-
201
- // Resolve symlinks to prevent traversal outside allowed paths
202
- let realPath = resolvedPath;
203
- try {
204
- realPath = fs.realpathSync(resolvedPath);
205
- } catch {
206
- // Path doesn't exist yet (e.g., createFolder) — resolve parent
207
- try {
208
- realPath = path.join(fs.realpathSync(path.dirname(resolvedPath)), path.basename(resolvedPath));
209
- } catch {
210
- // Parent doesn't exist either — keep lexical resolution
211
- }
212
- }
213
-
214
- // Check for sensitive directories — return metadata for auth challenge flow
215
- const matchedSensitiveDir = getSensitiveDir(realPath);
216
- if (matchedSensitiveDir) {
217
- return {
218
- valid: false,
219
- error: 'Access denied: sensitive directory',
220
- requiresAuth: true,
221
- sensitiveDir: matchedSensitiveDir
222
- };
223
- }
224
-
225
- // For browsing (listDirectory), allow access to home directory and below
226
- if (allowBrowse) {
227
- if (!isPathWithinBase(realPath, realHome)) {
228
- return {
229
- valid: false,
230
- error: 'Access denied: cannot browse outside home directory'
231
- };
232
- }
233
- return { valid: true, path: realPath };
234
- }
235
-
236
- // For write operations, enforce the allowedBasePath restriction
237
- if (!isPathWithinBase(realPath, realBase)) {
238
- return {
239
- valid: false,
240
- error: `Access denied: path outside allowed directory (${allowedBasePath})`
241
- };
242
- }
243
-
244
- return { valid: true, path: realPath };
245
- }
246
-
247
- /**
248
- * Escape content for tmux send-keys (literal mode)
249
- * @param {string} content - Content to escape
250
- * @returns {string}
251
- */
252
- function escapeForTmux(content) {
253
- if (!content || typeof content !== 'string') {
254
- return '';
255
- }
256
- // For tmux send-keys -l (literal mode), keep text unchanged except
257
- // for newline normalization. Caller handles splitting and Enter presses.
258
- return content.replace(/\r\n?/g, '\n');
259
- }
260
-
261
- /**
262
- * Validate number of lines for output capture
263
- * @param {number} lines - Number of lines
264
- * @returns {{ valid: boolean, sanitized: number }}
265
- */
266
- function validateLineCount(lines) {
267
- const num = parseInt(lines, 10);
268
- if (isNaN(num) || num < 1) {
269
- return { valid: true, sanitized: 500 }; // default
270
- }
271
- // Cap at 10000 lines to prevent memory issues
272
- return { valid: true, sanitized: Math.min(num, 10000) };
273
- }
274
-
275
- /**
276
- * Validate filename for upload
277
- * @param {string} name - Filename to validate
278
- * @returns {{ valid: boolean, error?: string }}
279
- */
280
- function validateFilename(name) {
281
- if (!name || typeof name !== 'string') {
282
- return { valid: false, error: 'Filename is required' };
283
- }
284
- if (name.length > 255) {
285
- return { valid: false, error: 'Filename too long (max 255 characters)' };
286
- }
287
- if (/\.\./.test(name) || /[/\\]/.test(name)) {
288
- return { valid: false, error: 'Filename contains invalid characters' };
289
- }
290
- if (/[\x00-\x1f\x7f]/.test(name)) {
291
- return { valid: false, error: 'Filename contains control characters' };
292
- }
293
- return { valid: true };
294
- }
295
-
296
- /**
297
- * Validate upload file size
298
- * @param {number} size - File size in bytes
299
- * @param {number} maxSize - Maximum allowed size (default 50MB)
300
- * @returns {{ valid: boolean, error?: string }}
301
- */
302
- function validateUploadSize(size, maxSize = 50 * 1024 * 1024) {
303
- if (typeof size !== 'number' || size <= 0) {
304
- return { valid: false, error: 'Invalid file size' };
305
- }
306
- if (size > maxSize) {
307
- return { valid: false, error: `File too large: ${(size / 1024 / 1024).toFixed(1)}MB exceeds ${(maxSize / 1024 / 1024)}MB limit` };
308
- }
309
- return { valid: true };
310
- }
311
-
312
- /**
313
- * Validate MIME type against whitelist
314
- * @param {string} mime - MIME type string
315
- * @returns {{ valid: boolean, error?: string }}
316
- */
317
- function validateMimeType(mime) {
318
- if (!mime || typeof mime !== 'string') {
319
- return { valid: false, error: 'MIME type is required' };
320
- }
321
- // Accept broad categories
322
- const allowedPrefixes = ['image/', 'text/', 'application/pdf', 'application/json',
323
- 'application/xml', 'application/zip', 'application/gzip', 'application/javascript',
324
- 'application/typescript', 'application/x-yaml', 'application/x-tar',
325
- 'application/x-7z-compressed', 'application/octet-stream',
326
- 'application/msword', 'application/vnd.openxmlformats', 'application/vnd.ms-'];
327
- const isAllowed = allowedPrefixes.some(prefix => mime.startsWith(prefix));
328
- if (!isAllowed) {
329
- return { valid: false, error: `Unsupported file type: ${mime}` };
330
- }
331
- return { valid: true };
332
- }
333
-
334
- module.exports = {
335
- validateSessionName,
336
- validateTmuxKey,
337
- validateClaudeCommand,
338
- validatePath,
339
- escapeForTmux,
340
- validateLineCount,
341
- getSensitiveDir,
342
- containsSensitiveDir,
343
- isPathWithinBase,
344
- validateFilename,
345
- validateUploadSize,
346
- validateMimeType,
347
- SESSION_NAME_RE,
348
- TMUX_KEY_ALLOWLIST,
349
- SENSITIVE_DIRS
350
- };