@myrialabs/clopen 0.3.12 → 0.3.14
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 +45 -1
- package/backend/auth/session-invalidation.ts +35 -1
- package/backend/chat/stream-manager.ts +15 -0
- package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/engine/README.md +16 -1597
- package/backend/engine/adapters/claude/message-converter.ts +34 -7
- package/backend/engine/adapters/claude/models.ts +174 -2
- 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/docs/adapter-contract.md +183 -0
- package/backend/engine/docs/adding-an-engine.md +150 -0
- package/backend/engine/docs/database.md +123 -0
- package/backend/engine/docs/frontend-and-chat.md +176 -0
- package/backend/engine/docs/lessons-learned.md +715 -0
- package/backend/engine/docs/quick-reference.md +36 -0
- package/backend/engine/docs/system-tools.md +82 -0
- package/backend/engine/docs/websocket-routes.md +240 -0
- package/backend/engine/structured-helpers.ts +59 -0
- package/backend/files/file-archive.test.ts +131 -0
- package/backend/files/file-archive.ts +252 -0
- package/backend/files/file-operations.ts +39 -66
- package/backend/files/file-size-limit.test.ts +71 -15
- package/backend/files/file-size-limit.ts +36 -8
- package/backend/files/file-watcher.ts +117 -3
- package/backend/http/files-upload.ts +168 -0
- package/backend/index.ts +8 -0
- package/backend/mcp/servers/helper.ts +5 -1
- package/backend/projects/project-cleanup.ts +1 -1
- package/backend/terminal/pty-session-manager.ts +3 -0
- package/backend/terminal/stream-manager.ts +1 -1
- package/backend/utils/ws.ts +9 -0
- package/backend/ws/auth/users.ts +1 -1
- package/backend/ws/chat/stream.ts +46 -38
- 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/watch.ts +48 -19
- package/backend/ws/files/write.ts +53 -27
- package/backend/ws/git/commit-message.ts +12 -5
- package/backend/ws/terminal/session.ts +1 -0
- package/dist/assets/main-BqiSLc8F.css +1 -0
- package/dist/assets/{main-HIDO3ugS.js → main-C37-Y8f-.js} +230 -229
- package/dist/index.html +2 -2
- package/package.json +8 -7
- package/shared/types/git.ts +4 -2
- package/shared/types/stores/settings.ts +2 -0
- package/shared/types/unified/index.ts +6 -0
- package/shared/types/unified/stream.ts +15 -1
- package/shared/types/unified/tool.ts +41 -1
- package/shared/utils/ws-server.ts +6 -0
- package/backend/engine/adapters/copilot/session-fork.ts +0 -111
- package/dist/assets/main-C2JiGYnx.css +0 -1
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
|
|
2
|
+
import { mkdir, readdir, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { zipSync, Unzip, UnzipInflate, UnzipPassThrough } 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 entryCount = await extractWithinLimit(data, targetDir, limit, limitMB);
|
|
143
|
+
|
|
144
|
+
const targetStats = await stat(targetDir);
|
|
145
|
+
return {
|
|
146
|
+
message: 'Archive extracted successfully',
|
|
147
|
+
path: targetDir,
|
|
148
|
+
entries: entryCount,
|
|
149
|
+
modified: targetStats.mtime.toISOString()
|
|
150
|
+
};
|
|
151
|
+
} catch (error) {
|
|
152
|
+
debug.error('file', 'Extract zip error:', error);
|
|
153
|
+
if (error instanceof Error) {
|
|
154
|
+
if (error.message.includes('EPERM')) {
|
|
155
|
+
throw new Error('Permission denied while extracting archive');
|
|
156
|
+
}
|
|
157
|
+
if (error.message.includes('ENOSPC')) {
|
|
158
|
+
throw new Error('Not enough space on disk');
|
|
159
|
+
}
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
throw new Error('Failed to extract archive');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const STREAM_CHUNK_SIZE = 64 * 1024;
|
|
167
|
+
|
|
168
|
+
function concatChunks(chunks: Uint8Array[], total: number): Uint8Array {
|
|
169
|
+
const out = new Uint8Array(total);
|
|
170
|
+
let pos = 0;
|
|
171
|
+
for (const chunk of chunks) {
|
|
172
|
+
out.set(chunk, pos);
|
|
173
|
+
pos += chunk.length;
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function writeEntry(fullPath: string, content: Uint8Array): Promise<void> {
|
|
179
|
+
await mkdir(dirname(fullPath), { recursive: true });
|
|
180
|
+
await writeFile(fullPath, content);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Stream-extract a ZIP, aborting as soon as the running total of *actual*
|
|
185
|
+
* decompressed bytes exceeds the limit. Feeding the compressed data in small
|
|
186
|
+
* chunks bounds how much a single decode step can emit, so a crafted archive
|
|
187
|
+
* cannot allocate more than the limit before being rejected — unlike trusting
|
|
188
|
+
* the uncompressed-size fields in the central directory, which an attacker
|
|
189
|
+
* controls and can forge to defeat a pre-decompression size check.
|
|
190
|
+
*/
|
|
191
|
+
async function extractWithinLimit(
|
|
192
|
+
data: Uint8Array,
|
|
193
|
+
targetDir: string,
|
|
194
|
+
limit: number,
|
|
195
|
+
limitMB: number
|
|
196
|
+
): Promise<number> {
|
|
197
|
+
let totalBytes = 0;
|
|
198
|
+
let entryCount = 0;
|
|
199
|
+
let failure: Error | null = null;
|
|
200
|
+
const writes: Promise<void>[] = [];
|
|
201
|
+
|
|
202
|
+
const unzipper = new Unzip((file) => {
|
|
203
|
+
if (failure) return;
|
|
204
|
+
|
|
205
|
+
if (!isSafeEntryPath(file.name, targetDir)) {
|
|
206
|
+
failure = new Error(`Unsafe path in archive: ${file.name}`);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const normalized = file.name.replace(/\\/g, '/');
|
|
211
|
+
const fullPath = join(targetDir, normalized.split('/').join(sep));
|
|
212
|
+
|
|
213
|
+
if (normalized.endsWith('/')) {
|
|
214
|
+
writes.push(mkdir(fullPath, { recursive: true }).then(() => undefined));
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const chunks: Uint8Array[] = [];
|
|
219
|
+
let fileBytes = 0;
|
|
220
|
+
file.ondata = (err, chunk, final) => {
|
|
221
|
+
if (failure) return;
|
|
222
|
+
if (err) {
|
|
223
|
+
failure = err;
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
totalBytes += chunk.length;
|
|
227
|
+
if (totalBytes > limit) {
|
|
228
|
+
failure = new Error(`Extracted content exceeds maximum allowed size of ${limitMB}MB`);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
chunks.push(chunk);
|
|
232
|
+
fileBytes += chunk.length;
|
|
233
|
+
if (final) {
|
|
234
|
+
writes.push(writeEntry(fullPath, concatChunks(chunks, fileBytes)));
|
|
235
|
+
entryCount++;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
file.start();
|
|
239
|
+
});
|
|
240
|
+
unzipper.register(UnzipInflate);
|
|
241
|
+
unzipper.register(UnzipPassThrough);
|
|
242
|
+
|
|
243
|
+
for (let offset = 0; offset < data.length && !failure; offset += STREAM_CHUNK_SIZE) {
|
|
244
|
+
const end = Math.min(offset + STREAM_CHUNK_SIZE, data.length);
|
|
245
|
+
unzipper.push(data.subarray(offset, end), end >= data.length);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (failure) throw failure;
|
|
249
|
+
await Promise.all(writes);
|
|
250
|
+
return entryCount;
|
|
251
|
+
}
|
|
252
|
+
|
|
@@ -112,7 +112,7 @@ async function rmdir(path: string, options?: { recursive?: boolean }) {
|
|
|
112
112
|
return rm(path, options);
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
-
export async function writeFileOperation(filePath: string, content: string) {
|
|
115
|
+
export async function writeFileOperation(filePath: string, content: string, baseModified?: string) {
|
|
116
116
|
if (!filePath) {
|
|
117
117
|
throw new Error('File path is required');
|
|
118
118
|
}
|
|
@@ -125,6 +125,26 @@ export async function writeFileOperation(filePath: string, content: string) {
|
|
|
125
125
|
const contentSize = Buffer.byteLength(content, 'utf8');
|
|
126
126
|
validateFileSize(contentSize);
|
|
127
127
|
|
|
128
|
+
// Optimistic concurrency: if the caller told us which on-disk version their
|
|
129
|
+
// content is based on, refuse to overwrite when the file has since changed.
|
|
130
|
+
// Skipped when the file no longer exists (treated as a fresh create) or when
|
|
131
|
+
// no base token is supplied (explicit force-write).
|
|
132
|
+
if (baseModified) {
|
|
133
|
+
try {
|
|
134
|
+
const currentStats = await fsStat(filePath);
|
|
135
|
+
if (currentStats.mtime.toISOString() !== baseModified) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
'FILE_CONFLICT: file changed on disk since it was last loaded'
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
} catch (err) {
|
|
141
|
+
if (err instanceof Error && err.message.startsWith('FILE_CONFLICT')) {
|
|
142
|
+
throw err;
|
|
143
|
+
}
|
|
144
|
+
// stat failed because the file is gone — fall through and create it.
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
128
148
|
try {
|
|
129
149
|
debug.log('file', 'Writing file:', { filePath, contentLength: content.length });
|
|
130
150
|
await Bun.write(filePath, content);
|
|
@@ -246,14 +266,22 @@ export async function renameOperation(oldPath: string, newPath: string) {
|
|
|
246
266
|
const normalizedNewPath = process.platform === 'win32' ?
|
|
247
267
|
newPath.replace(/\//g, '\\') : newPath;
|
|
248
268
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
269
|
+
// Use node:fs stat for existence checks (Bun.file().exists() returns
|
|
270
|
+
// false for directories, so it can't be used to rename folders).
|
|
271
|
+
try {
|
|
272
|
+
await fsStat(normalizedOldPath);
|
|
273
|
+
} catch {
|
|
253
274
|
throw new Error('Source path does not exist');
|
|
254
275
|
}
|
|
255
276
|
|
|
256
|
-
|
|
277
|
+
let destinationExists = false;
|
|
278
|
+
try {
|
|
279
|
+
await fsStat(normalizedNewPath);
|
|
280
|
+
destinationExists = true;
|
|
281
|
+
} catch {
|
|
282
|
+
// Destination does not exist — good.
|
|
283
|
+
}
|
|
284
|
+
if (destinationExists) {
|
|
257
285
|
throw new Error('Destination path already exists');
|
|
258
286
|
}
|
|
259
287
|
|
|
@@ -263,7 +291,7 @@ export async function renameOperation(oldPath: string, newPath: string) {
|
|
|
263
291
|
}
|
|
264
292
|
|
|
265
293
|
await rename(normalizedOldPath, normalizedNewPath);
|
|
266
|
-
const stats = await
|
|
294
|
+
const stats = await fsStat(normalizedNewPath);
|
|
267
295
|
|
|
268
296
|
return {
|
|
269
297
|
message: 'File/directory renamed successfully',
|
|
@@ -365,65 +393,10 @@ export async function duplicateOperation(sourcePath: string, targetPath: string)
|
|
|
365
393
|
}
|
|
366
394
|
}
|
|
367
395
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
if (!targetPath) {
|
|
374
|
-
throw new Error('Target path is required');
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// Validate the actual byte length of the payload, not the client-supplied
|
|
378
|
-
// `file.size` field — a mismatched value would otherwise bypass the limit.
|
|
379
|
-
validateFileSize(file.data.byteLength);
|
|
380
|
-
|
|
381
|
-
try {
|
|
382
|
-
// Normalize target path for Windows only
|
|
383
|
-
const normalizedTargetPath = process.platform === 'win32' ?
|
|
384
|
-
targetPath.replace(/\//g, '\\') : targetPath;
|
|
385
|
-
const finalPath = join(normalizedTargetPath, file.name);
|
|
386
|
-
|
|
387
|
-
// Create parent directory if it doesn't exist
|
|
388
|
-
const targetDir = Bun.file(normalizedTargetPath);
|
|
389
|
-
if (!(await targetDir.exists())) {
|
|
390
|
-
await mkdir(normalizedTargetPath, { recursive: true });
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
// Check if file already exists
|
|
394
|
-
const finalFile = Bun.file(finalPath);
|
|
395
|
-
if (await finalFile.exists()) {
|
|
396
|
-
throw new Error('File already exists');
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
// Write file
|
|
400
|
-
await Bun.write(finalPath, file.data);
|
|
401
|
-
const stats = await finalFile.stat();
|
|
402
|
-
|
|
403
|
-
return {
|
|
404
|
-
message: 'File uploaded successfully',
|
|
405
|
-
path: finalPath,
|
|
406
|
-
size: stats.size,
|
|
407
|
-
modified: stats.mtime.toISOString()
|
|
408
|
-
};
|
|
409
|
-
} catch (error) {
|
|
410
|
-
debug.error('file', 'Upload file error:', error);
|
|
411
|
-
if (error instanceof Error) {
|
|
412
|
-
if (error.message === 'File already exists') {
|
|
413
|
-
throw error;
|
|
414
|
-
}
|
|
415
|
-
if (error.message.includes('EPERM')) {
|
|
416
|
-
throw new Error('Permission denied - you may not have sufficient permissions to upload files to this location');
|
|
417
|
-
} else if (error.message.includes('ENOENT')) {
|
|
418
|
-
throw new Error('Target directory does not exist or is invalid');
|
|
419
|
-
} else if (error.message.includes('ENOSPC')) {
|
|
420
|
-
throw new Error('Not enough space on disk');
|
|
421
|
-
}
|
|
422
|
-
throw error;
|
|
423
|
-
}
|
|
424
|
-
throw new Error('Failed to upload file');
|
|
425
|
-
}
|
|
426
|
-
}
|
|
396
|
+
// Upload is served by the HTTP route (backend/http/files-upload.ts). The
|
|
397
|
+
// earlier WS-based chunked uploader was removed because the Vite dev proxy
|
|
398
|
+
// dropped sustained WS binary transfers with `write EPIPE`, regardless of
|
|
399
|
+
// chunk size.
|
|
427
400
|
|
|
428
401
|
export async function deleteOperation(filePath: string, force: boolean = false) {
|
|
429
402
|
if (!filePath) {
|
|
@@ -1,29 +1,85 @@
|
|
|
1
|
-
import { describe, expect, test } from 'bun:test';
|
|
2
|
-
|
|
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
|
+
});
|
|
3
25
|
|
|
4
|
-
describe('validateFileSize', () => {
|
|
5
26
|
test('accepts files within the default size limit', () => {
|
|
6
|
-
|
|
7
|
-
const withinLimit = 50 * 1024 * 1024; // 50MB
|
|
8
|
-
expect(() => validateFileSize(withinLimit)).not.toThrow();
|
|
27
|
+
expect(() => validateFileSize(defaultLimitBytes)).not.toThrow();
|
|
9
28
|
});
|
|
10
29
|
|
|
11
30
|
test('rejects files exceeding the default size limit', () => {
|
|
12
|
-
|
|
13
|
-
expect(() => validateFileSize(overLimit)).toThrow(/File size exceeds/);
|
|
31
|
+
expect(() => validateFileSize(defaultLimitBytes + 1)).toThrow(/File size exceeds/);
|
|
14
32
|
});
|
|
15
33
|
|
|
16
34
|
test('accepts small files', () => {
|
|
17
|
-
expect(() => validateFileSize(1024)).not.toThrow();
|
|
18
|
-
expect(() => validateFileSize(0)).not.toThrow();
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
test('rejects very large files', () => {
|
|
22
|
-
const huge = 500 * 1024 * 1024; // 500MB
|
|
23
|
-
expect(() => validateFileSize(huge)).toThrow(/File size exceeds/);
|
|
35
|
+
expect(() => validateFileSize(1024)).not.toThrow();
|
|
36
|
+
expect(() => validateFileSize(0)).not.toThrow();
|
|
24
37
|
});
|
|
25
38
|
|
|
26
39
|
test('rejects negative sizes', () => {
|
|
27
40
|
expect(() => validateFileSize(-1)).toThrow(/Invalid file size/);
|
|
28
41
|
});
|
|
29
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
|
+
});
|
|
@@ -1,24 +1,52 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* File Size Limit Validation
|
|
3
3
|
*
|
|
4
|
-
* Enforces maximum file size
|
|
5
|
-
* to prevent disk exhaustion attacks (DoS).
|
|
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.
|
|
6
8
|
*/
|
|
7
9
|
|
|
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
|
+
}
|
|
10
37
|
|
|
11
38
|
/**
|
|
12
|
-
* Validate that a file size is within the
|
|
39
|
+
* Validate that a file size is within the configured limit.
|
|
13
40
|
* @param size - File size in bytes
|
|
14
|
-
* @throws Error if size is negative or exceeds
|
|
41
|
+
* @throws Error if size is negative or exceeds the configured maximum
|
|
15
42
|
*/
|
|
16
43
|
export function validateFileSize(size: number): void {
|
|
17
44
|
if (size < 0) {
|
|
18
45
|
throw new Error('Invalid file size: size cannot be negative');
|
|
19
46
|
}
|
|
20
|
-
|
|
21
|
-
|
|
47
|
+
const limit = getMaxFileSize();
|
|
48
|
+
if (size > limit) {
|
|
49
|
+
const maxMB = Math.floor(limit / (1024 * 1024));
|
|
22
50
|
throw new Error(`File size exceeds maximum allowed size of ${maxMB}MB`);
|
|
23
51
|
}
|
|
24
52
|
}
|