@myrialabs/clopen 0.3.11 → 0.3.13
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/backend/auth/session-invalidation.test.ts +116 -0
- package/backend/auth/session-invalidation.ts +78 -0
- package/backend/chat/stream-manager.ts +4 -0
- package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
- package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/audit-log-queries.test.ts +162 -0
- package/backend/database/queries/audit-log-queries.ts +98 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/engine/README.md +101 -29
- package/backend/engine/adapters/claude/message-converter.ts +1 -0
- package/backend/engine/adapters/codex/stream.ts +54 -1
- package/backend/engine/adapters/copilot/stream.ts +79 -19
- package/backend/engine/adapters/opencode/stream.ts +23 -23
- package/backend/engine/adapters/qwen/stream.ts +83 -1
- package/backend/engine/structured-helpers.ts +59 -0
- package/backend/files/file-archive.ts +191 -0
- package/backend/files/file-operations.ts +25 -61
- package/backend/files/file-size-limit.test.ts +85 -0
- package/backend/files/file-size-limit.ts +52 -0
- package/backend/git/git-service.ts +48 -4
- package/backend/http/files-upload.ts +168 -0
- package/backend/index.ts +14 -0
- package/backend/mcp/config.ts +4 -1
- package/backend/mcp/output-validator.test.ts +52 -0
- package/backend/mcp/output-validator.ts +103 -0
- package/backend/mcp/project-context.test.ts +22 -0
- package/backend/mcp/project-context.ts +35 -0
- package/backend/mcp/servers/helper.ts +11 -2
- package/backend/project/status-manager.test.ts +32 -0
- package/backend/project/status-manager.ts +7 -0
- package/backend/projects/project-cleanup-registry.test.ts +48 -0
- package/backend/projects/project-cleanup-registry.ts +44 -0
- package/backend/projects/project-cleanup.integration.test.ts +36 -0
- package/backend/projects/project-cleanup.ts +32 -0
- package/backend/terminal/pty-session-manager.ts +3 -0
- package/backend/terminal/stream-manager.ts +1 -1
- package/backend/utils/ws.ts +46 -0
- package/backend/ws/auth/index.ts +4 -0
- package/backend/ws/auth/login.ts +31 -19
- package/backend/ws/auth/users.ts +21 -2
- package/backend/ws/chat/stream.ts +11 -0
- package/backend/ws/files/path-access.test.ts +166 -0
- package/backend/ws/files/path-access.ts +56 -22
- package/backend/ws/files/read.ts +5 -5
- package/backend/ws/files/search.ts +4 -0
- package/backend/ws/files/write.ts +47 -25
- package/backend/ws/git/commit-message.ts +12 -5
- package/backend/ws/git/remote.ts +6 -3
- package/backend/ws/message-rate-limiter.test.ts +79 -0
- package/backend/ws/message-rate-limiter.ts +134 -0
- package/backend/ws/projects/crud.ts +3 -0
- package/backend/ws/terminal/session.ts +1 -0
- package/dist/assets/main-BqiSLc8F.css +1 -0
- package/dist/assets/main-DOVudc3_.js +354 -0
- package/dist/index.html +2 -2
- package/package.json +8 -7
- package/shared/types/git.ts +4 -2
- package/shared/types/stores/settings.ts +4 -0
- package/shared/types/unified/index.ts +1 -0
- package/shared/types/unified/stream.ts +8 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +17 -6
- package/backend/engine/adapters/copilot/session-fork.ts +0 -111
- package/dist/assets/index-DmghE6mf.js +0 -2
- package/dist/assets/main-DiDuzJJh.js +0 -318
- package/dist/assets/main-N1w7Llvp.css +0 -1
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
|
|
2
|
+
import { mkdir, readdir, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { zipSync, unzipSync } from 'fflate';
|
|
4
|
+
|
|
5
|
+
import { debug } from '$shared/utils/logger';
|
|
6
|
+
import { getMaxFileSize, validateFileSize } from './file-size-limit';
|
|
7
|
+
|
|
8
|
+
interface ZipTree {
|
|
9
|
+
[path: string]: Uint8Array | ZipTree;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function setInTree(tree: ZipTree, parts: string[], value: Uint8Array | ZipTree): void {
|
|
13
|
+
if (parts.length === 0) return;
|
|
14
|
+
if (parts.length === 1) {
|
|
15
|
+
tree[parts[0]] = value;
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const head = parts[0];
|
|
19
|
+
const existing = tree[head];
|
|
20
|
+
const child: ZipTree = existing && !(existing instanceof Uint8Array)
|
|
21
|
+
? (existing as ZipTree)
|
|
22
|
+
: {};
|
|
23
|
+
tree[head] = child;
|
|
24
|
+
setInTree(child, parts.slice(1), value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function readPathIntoTree(sourcePath: string, rootName: string, tree: ZipTree): Promise<void> {
|
|
28
|
+
const stats = await stat(sourcePath);
|
|
29
|
+
if (stats.isFile()) {
|
|
30
|
+
const data = new Uint8Array(await Bun.file(sourcePath).arrayBuffer());
|
|
31
|
+
setInTree(tree, rootName.split('/'), data);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (stats.isDirectory()) {
|
|
35
|
+
const entries = await readdir(sourcePath);
|
|
36
|
+
if (entries.length === 0) {
|
|
37
|
+
setInTree(tree, rootName.split('/'), {} as ZipTree);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
await readPathIntoTree(
|
|
42
|
+
join(sourcePath, entry),
|
|
43
|
+
`${rootName}/${entry}`,
|
|
44
|
+
tree
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function createZipOperation(sourcePaths: string[], targetZipPath: string): Promise<{ message: string; path: string; size: number; modified: string }> {
|
|
51
|
+
if (!Array.isArray(sourcePaths) || sourcePaths.length === 0) {
|
|
52
|
+
throw new Error('At least one source path is required');
|
|
53
|
+
}
|
|
54
|
+
if (!targetZipPath) {
|
|
55
|
+
throw new Error('Target zip path is required');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const targetFile = Bun.file(targetZipPath);
|
|
60
|
+
if (await targetFile.exists()) {
|
|
61
|
+
throw new Error('Target archive already exists');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const tree: ZipTree = {};
|
|
65
|
+
|
|
66
|
+
for (const source of sourcePaths) {
|
|
67
|
+
const name = basename(source);
|
|
68
|
+
if (!name || name === '.' || name === '..') {
|
|
69
|
+
throw new Error(`Invalid source path: ${source}`);
|
|
70
|
+
}
|
|
71
|
+
await readPathIntoTree(source, name, tree);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const zipped = zipSync(tree as Record<string, Uint8Array>, { level: 6 });
|
|
75
|
+
validateFileSize(zipped.byteLength);
|
|
76
|
+
await Bun.write(targetZipPath, zipped);
|
|
77
|
+
const stats = await stat(targetZipPath);
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
message: 'Archive created successfully',
|
|
81
|
+
path: targetZipPath,
|
|
82
|
+
size: stats.size,
|
|
83
|
+
modified: stats.mtime.toISOString()
|
|
84
|
+
};
|
|
85
|
+
} catch (error) {
|
|
86
|
+
debug.error('file', 'Create zip error:', error);
|
|
87
|
+
if (error instanceof Error) {
|
|
88
|
+
if (error.message.includes('EPERM')) {
|
|
89
|
+
throw new Error('Permission denied while creating archive');
|
|
90
|
+
}
|
|
91
|
+
if (error.message.includes('ENOSPC')) {
|
|
92
|
+
throw new Error('Not enough space on disk');
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
throw new Error('Failed to create archive');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function isSafeEntryPath(entryPath: string, targetRoot: string): boolean {
|
|
101
|
+
if (!entryPath) return false;
|
|
102
|
+
if (isAbsolute(entryPath)) return false;
|
|
103
|
+
const normalized = entryPath.replace(/\\/g, '/');
|
|
104
|
+
if (normalized.split('/').some((segment) => segment === '..')) return false;
|
|
105
|
+
const full = join(targetRoot, normalized);
|
|
106
|
+
const rel = relative(targetRoot, full);
|
|
107
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function extractZipOperation(archivePath: string, targetDir: string): Promise<{ message: string; path: string; entries: number; modified: string }> {
|
|
111
|
+
if (!archivePath) {
|
|
112
|
+
throw new Error('Archive path is required');
|
|
113
|
+
}
|
|
114
|
+
if (!targetDir) {
|
|
115
|
+
throw new Error('Target directory is required');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const archiveFile = Bun.file(archivePath);
|
|
119
|
+
if (!(await archiveFile.exists())) {
|
|
120
|
+
throw new Error('Archive does not exist');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const limit = getMaxFileSize();
|
|
124
|
+
const limitMB = Math.floor(limit / (1024 * 1024));
|
|
125
|
+
const stats = await stat(archivePath);
|
|
126
|
+
if (stats.size > limit) {
|
|
127
|
+
throw new Error(`Archive exceeds maximum allowed size of ${limitMB}MB`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
const targetExists = await Bun.file(targetDir).exists();
|
|
132
|
+
if (targetExists) {
|
|
133
|
+
const targetStats = await stat(targetDir);
|
|
134
|
+
if (!targetStats.isDirectory()) {
|
|
135
|
+
throw new Error('Target path exists and is not a directory');
|
|
136
|
+
}
|
|
137
|
+
} else {
|
|
138
|
+
await mkdir(targetDir, { recursive: true });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const data = new Uint8Array(await archiveFile.arrayBuffer());
|
|
142
|
+
const unzipped = unzipSync(data);
|
|
143
|
+
|
|
144
|
+
let totalBytes = 0;
|
|
145
|
+
for (const buf of Object.values(unzipped)) {
|
|
146
|
+
totalBytes += buf.byteLength;
|
|
147
|
+
if (totalBytes > limit) {
|
|
148
|
+
throw new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let entryCount = 0;
|
|
153
|
+
for (const [entryPath, content] of Object.entries(unzipped)) {
|
|
154
|
+
if (!isSafeEntryPath(entryPath, targetDir)) {
|
|
155
|
+
throw new Error(`Unsafe path in archive: ${entryPath}`);
|
|
156
|
+
}
|
|
157
|
+
const normalized = entryPath.replace(/\\/g, '/');
|
|
158
|
+
const isDirEntry = normalized.endsWith('/');
|
|
159
|
+
const fullPath = join(targetDir, normalized.split('/').join(sep));
|
|
160
|
+
|
|
161
|
+
if (isDirEntry) {
|
|
162
|
+
await mkdir(fullPath, { recursive: true });
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
await mkdir(dirname(fullPath), { recursive: true });
|
|
166
|
+
await writeFile(fullPath, content);
|
|
167
|
+
entryCount++;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const targetStats = await stat(targetDir);
|
|
171
|
+
return {
|
|
172
|
+
message: 'Archive extracted successfully',
|
|
173
|
+
path: targetDir,
|
|
174
|
+
entries: entryCount,
|
|
175
|
+
modified: targetStats.mtime.toISOString()
|
|
176
|
+
};
|
|
177
|
+
} catch (error) {
|
|
178
|
+
debug.error('file', 'Extract zip error:', error);
|
|
179
|
+
if (error instanceof Error) {
|
|
180
|
+
if (error.message.includes('EPERM')) {
|
|
181
|
+
throw new Error('Permission denied while extracting archive');
|
|
182
|
+
}
|
|
183
|
+
if (error.message.includes('ENOSPC')) {
|
|
184
|
+
throw new Error('Not enough space on disk');
|
|
185
|
+
}
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
throw new Error('Failed to extract archive');
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
@@ -2,6 +2,7 @@ import { dirname, extname, join } from 'path';
|
|
|
2
2
|
import { stat as fsStat } from 'node:fs/promises';
|
|
3
3
|
|
|
4
4
|
import { debug } from '$shared/utils/logger';
|
|
5
|
+
import { validateFileSize } from './file-size-limit';
|
|
5
6
|
|
|
6
7
|
// Import Bun native functions and create wrappers for better API compatibility
|
|
7
8
|
const { spawn } = Bun;
|
|
@@ -120,6 +121,10 @@ export async function writeFileOperation(filePath: string, content: string) {
|
|
|
120
121
|
throw new Error('Content must be a string');
|
|
121
122
|
}
|
|
122
123
|
|
|
124
|
+
// Validate content size before writing
|
|
125
|
+
const contentSize = Buffer.byteLength(content, 'utf8');
|
|
126
|
+
validateFileSize(contentSize);
|
|
127
|
+
|
|
123
128
|
try {
|
|
124
129
|
debug.log('file', 'Writing file:', { filePath, contentLength: content.length });
|
|
125
130
|
await Bun.write(filePath, content);
|
|
@@ -143,6 +148,8 @@ export async function createFileOperation(filePath: string, content: string = ''
|
|
|
143
148
|
throw new Error('File path is required');
|
|
144
149
|
}
|
|
145
150
|
|
|
151
|
+
validateFileSize(Buffer.byteLength(content, 'utf8'));
|
|
152
|
+
|
|
146
153
|
try {
|
|
147
154
|
// Normalize path for Windows only
|
|
148
155
|
const normalizedFilePath = process.platform === 'win32' ?
|
|
@@ -239,14 +246,22 @@ export async function renameOperation(oldPath: string, newPath: string) {
|
|
|
239
246
|
const normalizedNewPath = process.platform === 'win32' ?
|
|
240
247
|
newPath.replace(/\//g, '\\') : newPath;
|
|
241
248
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
249
|
+
// Use node:fs stat for existence checks (Bun.file().exists() returns
|
|
250
|
+
// false for directories, so it can't be used to rename folders).
|
|
251
|
+
try {
|
|
252
|
+
await fsStat(normalizedOldPath);
|
|
253
|
+
} catch {
|
|
246
254
|
throw new Error('Source path does not exist');
|
|
247
255
|
}
|
|
248
256
|
|
|
249
|
-
|
|
257
|
+
let destinationExists = false;
|
|
258
|
+
try {
|
|
259
|
+
await fsStat(normalizedNewPath);
|
|
260
|
+
destinationExists = true;
|
|
261
|
+
} catch {
|
|
262
|
+
// Destination does not exist — good.
|
|
263
|
+
}
|
|
264
|
+
if (destinationExists) {
|
|
250
265
|
throw new Error('Destination path already exists');
|
|
251
266
|
}
|
|
252
267
|
|
|
@@ -256,7 +271,7 @@ export async function renameOperation(oldPath: string, newPath: string) {
|
|
|
256
271
|
}
|
|
257
272
|
|
|
258
273
|
await rename(normalizedOldPath, normalizedNewPath);
|
|
259
|
-
const stats = await
|
|
274
|
+
const stats = await fsStat(normalizedNewPath);
|
|
260
275
|
|
|
261
276
|
return {
|
|
262
277
|
message: 'File/directory renamed successfully',
|
|
@@ -358,61 +373,10 @@ export async function duplicateOperation(sourcePath: string, targetPath: string)
|
|
|
358
373
|
}
|
|
359
374
|
}
|
|
360
375
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
if (!targetPath) {
|
|
367
|
-
throw new Error('Target path is required');
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
try {
|
|
371
|
-
// Normalize target path for Windows only
|
|
372
|
-
const normalizedTargetPath = process.platform === 'win32' ?
|
|
373
|
-
targetPath.replace(/\//g, '\\') : targetPath;
|
|
374
|
-
const finalPath = join(normalizedTargetPath, file.name);
|
|
375
|
-
|
|
376
|
-
// Create parent directory if it doesn't exist
|
|
377
|
-
const targetDir = Bun.file(normalizedTargetPath);
|
|
378
|
-
if (!(await targetDir.exists())) {
|
|
379
|
-
await mkdir(normalizedTargetPath, { recursive: true });
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
// Check if file already exists
|
|
383
|
-
const finalFile = Bun.file(finalPath);
|
|
384
|
-
if (await finalFile.exists()) {
|
|
385
|
-
throw new Error('File already exists');
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
// Write file
|
|
389
|
-
await Bun.write(finalPath, file.data);
|
|
390
|
-
const stats = await finalFile.stat();
|
|
391
|
-
|
|
392
|
-
return {
|
|
393
|
-
message: 'File uploaded successfully',
|
|
394
|
-
path: finalPath,
|
|
395
|
-
size: stats.size,
|
|
396
|
-
modified: stats.mtime.toISOString()
|
|
397
|
-
};
|
|
398
|
-
} catch (error) {
|
|
399
|
-
debug.error('file', 'Upload file error:', error);
|
|
400
|
-
if (error instanceof Error) {
|
|
401
|
-
if (error.message === 'File already exists') {
|
|
402
|
-
throw error;
|
|
403
|
-
}
|
|
404
|
-
if (error.message.includes('EPERM')) {
|
|
405
|
-
throw new Error('Permission denied - you may not have sufficient permissions to upload files to this location');
|
|
406
|
-
} else if (error.message.includes('ENOENT')) {
|
|
407
|
-
throw new Error('Target directory does not exist or is invalid');
|
|
408
|
-
} else if (error.message.includes('ENOSPC')) {
|
|
409
|
-
throw new Error('Not enough space on disk');
|
|
410
|
-
}
|
|
411
|
-
throw error;
|
|
412
|
-
}
|
|
413
|
-
throw new Error('Failed to upload file');
|
|
414
|
-
}
|
|
415
|
-
}
|
|
376
|
+
// Upload is served by the HTTP route (backend/http/files-upload.ts). The
|
|
377
|
+
// earlier WS-based chunked uploader was removed because the Vite dev proxy
|
|
378
|
+
// dropped sustained WS binary transfers with `write EPIPE`, regardless of
|
|
379
|
+
// chunk size.
|
|
416
380
|
|
|
417
381
|
export async function deleteOperation(filePath: string, force: boolean = false) {
|
|
418
382
|
if (!filePath) {
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { DEFAULT_MAX_FILE_SIZE_MB } from './file-size-limit';
|
|
4
|
+
|
|
5
|
+
const defaultLimitBytes = DEFAULT_MAX_FILE_SIZE_MB * 1024 * 1024;
|
|
6
|
+
|
|
7
|
+
// Stub settingsQueries before importing the module under test so the
|
|
8
|
+
// `system:settings` lookup never touches a real database during unit tests.
|
|
9
|
+
let mockSettingsRow: { key: string; value: string; updated_at: string } | null = null;
|
|
10
|
+
await mock.module('../database/queries', () => ({
|
|
11
|
+
settingsQueries: {
|
|
12
|
+
get: (_key: string) => mockSettingsRow,
|
|
13
|
+
getAll: () => [],
|
|
14
|
+
set: () => {},
|
|
15
|
+
delete: () => {}
|
|
16
|
+
}
|
|
17
|
+
}));
|
|
18
|
+
|
|
19
|
+
const { validateFileSize } = await import('./file-size-limit');
|
|
20
|
+
|
|
21
|
+
describe('validateFileSize (default limit)', () => {
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
mockSettingsRow = null;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('accepts files within the default size limit', () => {
|
|
27
|
+
expect(() => validateFileSize(defaultLimitBytes)).not.toThrow();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('rejects files exceeding the default size limit', () => {
|
|
31
|
+
expect(() => validateFileSize(defaultLimitBytes + 1)).toThrow(/File size exceeds/);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('accepts small files', () => {
|
|
35
|
+
expect(() => validateFileSize(1024)).not.toThrow();
|
|
36
|
+
expect(() => validateFileSize(0)).not.toThrow();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('rejects negative sizes', () => {
|
|
40
|
+
expect(() => validateFileSize(-1)).toThrow(/Invalid file size/);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('validateFileSize (configurable limit)', () => {
|
|
45
|
+
afterEach(() => {
|
|
46
|
+
mockSettingsRow = null;
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('honors a higher admin-configured limit', () => {
|
|
50
|
+
mockSettingsRow = {
|
|
51
|
+
key: 'system:settings',
|
|
52
|
+
value: JSON.stringify({ maxFileSizeMB: 1024 }),
|
|
53
|
+
updated_at: ''
|
|
54
|
+
};
|
|
55
|
+
expect(() => validateFileSize(800 * 1024 * 1024)).not.toThrow();
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('honors a lower admin-configured limit', () => {
|
|
59
|
+
mockSettingsRow = {
|
|
60
|
+
key: 'system:settings',
|
|
61
|
+
value: JSON.stringify({ maxFileSizeMB: 10 }),
|
|
62
|
+
updated_at: ''
|
|
63
|
+
};
|
|
64
|
+
expect(() => validateFileSize(11 * 1024 * 1024)).toThrow(/File size exceeds/);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('falls back to the default when the value is malformed', () => {
|
|
68
|
+
mockSettingsRow = {
|
|
69
|
+
key: 'system:settings',
|
|
70
|
+
value: '{ not json',
|
|
71
|
+
updated_at: ''
|
|
72
|
+
};
|
|
73
|
+
expect(() => validateFileSize(defaultLimitBytes)).not.toThrow();
|
|
74
|
+
expect(() => validateFileSize(defaultLimitBytes + 1)).toThrow(/File size exceeds/);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('falls back to the default when maxFileSizeMB is non-positive', () => {
|
|
78
|
+
mockSettingsRow = {
|
|
79
|
+
key: 'system:settings',
|
|
80
|
+
value: JSON.stringify({ maxFileSizeMB: 0 }),
|
|
81
|
+
updated_at: ''
|
|
82
|
+
};
|
|
83
|
+
expect(() => validateFileSize(defaultLimitBytes)).not.toThrow();
|
|
84
|
+
});
|
|
85
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Size Limit Validation
|
|
3
|
+
*
|
|
4
|
+
* Enforces a configurable maximum file size on write, upload, zip, and
|
|
5
|
+
* extract operations to prevent disk exhaustion attacks (DoS). The limit
|
|
6
|
+
* is sourced from the `system:settings.maxFileSizeMB` admin setting and
|
|
7
|
+
* defaults to 500MB when the setting is missing or invalid.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { settingsQueries } from '../database/queries';
|
|
11
|
+
|
|
12
|
+
/** Default maximum file size in megabytes when no admin setting is present. */
|
|
13
|
+
export const DEFAULT_MAX_FILE_SIZE_MB = 500;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Read the current maximum file size (bytes) from system settings.
|
|
17
|
+
* Falls back to the default if the row is missing, malformed, or holds a
|
|
18
|
+
* non-positive value — keeps callers resilient even if the DB is empty
|
|
19
|
+
* (e.g. on first boot before the admin writes any system setting).
|
|
20
|
+
*/
|
|
21
|
+
export function getMaxFileSize(): number {
|
|
22
|
+
let limitMB = DEFAULT_MAX_FILE_SIZE_MB;
|
|
23
|
+
try {
|
|
24
|
+
const row = settingsQueries.get('system:settings');
|
|
25
|
+
if (row?.value) {
|
|
26
|
+
const parsed = typeof row.value === 'string' ? JSON.parse(row.value) : row.value;
|
|
27
|
+
const candidate = Number(parsed?.maxFileSizeMB);
|
|
28
|
+
if (Number.isFinite(candidate) && candidate > 0) {
|
|
29
|
+
limitMB = candidate;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
} catch {
|
|
33
|
+
// Fall back to default on any read/parse failure.
|
|
34
|
+
}
|
|
35
|
+
return Math.floor(limitMB * 1024 * 1024);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Validate that a file size is within the configured limit.
|
|
40
|
+
* @param size - File size in bytes
|
|
41
|
+
* @throws Error if size is negative or exceeds the configured maximum
|
|
42
|
+
*/
|
|
43
|
+
export function validateFileSize(size: number): void {
|
|
44
|
+
if (size < 0) {
|
|
45
|
+
throw new Error('Invalid file size: size cannot be negative');
|
|
46
|
+
}
|
|
47
|
+
const limit = getMaxFileSize();
|
|
48
|
+
if (size > limit) {
|
|
49
|
+
const maxMB = Math.floor(limit / (1024 * 1024));
|
|
50
|
+
throw new Error(`File size exceeds maximum allowed size of ${maxMB}MB`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -447,14 +447,26 @@ export class GitService {
|
|
|
447
447
|
}
|
|
448
448
|
}
|
|
449
449
|
|
|
450
|
-
async stashPop(
|
|
450
|
+
async stashPop(
|
|
451
|
+
cwd: string,
|
|
452
|
+
index = 0
|
|
453
|
+
): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
|
|
451
454
|
if (!Number.isInteger(index) || index < 0) {
|
|
452
455
|
throw new Error('Invalid stash index');
|
|
453
456
|
}
|
|
454
457
|
const result = await execGit(['stash', 'pop', `stash@{${index}}`], cwd);
|
|
458
|
+
// Conflict during pop: git exits non-zero but the working tree now contains
|
|
459
|
+
// unmerged paths. Surface this as a normal result so the caller can prompt
|
|
460
|
+
// the user to resolve — throwing here would just produce an opaque toast.
|
|
461
|
+
const combined = `${result.stdout}\n${result.stderr}`;
|
|
462
|
+
const hasConflicts = /CONFLICT \(/.test(combined) || /needs merge/.test(combined);
|
|
455
463
|
if (result.exitCode !== 0) {
|
|
464
|
+
if (hasConflicts) {
|
|
465
|
+
return { success: false, hasConflicts: true, message: result.stderr || result.stdout };
|
|
466
|
+
}
|
|
456
467
|
throw new Error(`git stash pop failed: ${result.stderr}`);
|
|
457
468
|
}
|
|
469
|
+
return { success: true, hasConflicts: false, message: result.stdout };
|
|
458
470
|
}
|
|
459
471
|
|
|
460
472
|
async stashDrop(cwd: string, index = 0): Promise<void> {
|
|
@@ -577,10 +589,42 @@ export class GitService {
|
|
|
577
589
|
await this.stageFile(cwd, filePath);
|
|
578
590
|
}
|
|
579
591
|
|
|
592
|
+
/**
|
|
593
|
+
* Aborts the in-progress conflict-producing operation: merge, cherry-pick,
|
|
594
|
+
* revert, rebase, or a stash pop that left unmerged paths. We detect the
|
|
595
|
+
* type via `.git/*_HEAD` sentinel files and pick the matching abort command.
|
|
596
|
+
* For stash conflicts (no sentinel) we fall back to `git reset --merge`,
|
|
597
|
+
* which unwinds the unmerged paths while keeping unrelated local edits.
|
|
598
|
+
*/
|
|
580
599
|
async abortMerge(cwd: string): Promise<void> {
|
|
581
|
-
const
|
|
582
|
-
|
|
583
|
-
|
|
600
|
+
const { existsSync } = await import('node:fs');
|
|
601
|
+
const { join } = await import('node:path');
|
|
602
|
+
|
|
603
|
+
const gitDirResult = await execGit(['rev-parse', '--git-dir'], cwd);
|
|
604
|
+
const gitDirRaw = gitDirResult.exitCode === 0 ? gitDirResult.stdout.trim() : '.git';
|
|
605
|
+
const gitDir = gitDirRaw.startsWith('/') ? gitDirRaw : join(cwd, gitDirRaw);
|
|
606
|
+
|
|
607
|
+
const has = (name: string) => existsSync(join(gitDir, name));
|
|
608
|
+
|
|
609
|
+
let args: string[] | null = null;
|
|
610
|
+
if (has('MERGE_HEAD')) args = ['merge', '--abort'];
|
|
611
|
+
else if (has('CHERRY_PICK_HEAD')) args = ['cherry-pick', '--abort'];
|
|
612
|
+
else if (has('REVERT_HEAD')) args = ['revert', '--abort'];
|
|
613
|
+
else if (has('rebase-merge') || has('rebase-apply')) args = ['rebase', '--abort'];
|
|
614
|
+
|
|
615
|
+
if (args) {
|
|
616
|
+
const result = await execGit(args, cwd);
|
|
617
|
+
if (result.exitCode !== 0) {
|
|
618
|
+
throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`);
|
|
619
|
+
}
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// No standard in-progress operation — likely a stash pop conflict. Use
|
|
624
|
+
// `git reset --merge` to unwind unmerged paths safely.
|
|
625
|
+
const reset = await execGit(['reset', '--merge'], cwd);
|
|
626
|
+
if (reset.exitCode !== 0) {
|
|
627
|
+
throw new Error(`git reset --merge failed: ${reset.stderr}`);
|
|
584
628
|
}
|
|
585
629
|
}
|
|
586
630
|
}
|