@myrialabs/clopen 0.3.12 → 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.
Files changed (35) hide show
  1. package/backend/auth/session-invalidation.test.ts +45 -1
  2. package/backend/auth/session-invalidation.ts +35 -1
  3. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/engine/README.md +101 -29
  6. package/backend/engine/adapters/codex/stream.ts +54 -1
  7. package/backend/engine/adapters/copilot/stream.ts +79 -19
  8. package/backend/engine/adapters/opencode/stream.ts +23 -23
  9. package/backend/engine/adapters/qwen/stream.ts +83 -1
  10. package/backend/engine/structured-helpers.ts +59 -0
  11. package/backend/files/file-archive.ts +191 -0
  12. package/backend/files/file-operations.ts +18 -65
  13. package/backend/files/file-size-limit.test.ts +71 -15
  14. package/backend/files/file-size-limit.ts +36 -8
  15. package/backend/http/files-upload.ts +168 -0
  16. package/backend/index.ts +8 -0
  17. package/backend/mcp/servers/helper.ts +5 -1
  18. package/backend/terminal/pty-session-manager.ts +3 -0
  19. package/backend/terminal/stream-manager.ts +1 -1
  20. package/backend/ws/auth/users.ts +1 -1
  21. package/backend/ws/files/path-access.test.ts +166 -0
  22. package/backend/ws/files/path-access.ts +56 -22
  23. package/backend/ws/files/read.ts +5 -5
  24. package/backend/ws/files/write.ts +47 -25
  25. package/backend/ws/git/commit-message.ts +12 -5
  26. package/backend/ws/terminal/session.ts +1 -0
  27. package/dist/assets/main-BqiSLc8F.css +1 -0
  28. package/dist/assets/{main-HIDO3ugS.js → main-DOVudc3_.js} +232 -231
  29. package/dist/index.html +2 -2
  30. package/package.json +8 -7
  31. package/shared/types/git.ts +4 -2
  32. package/shared/types/stores/settings.ts +2 -0
  33. package/shared/utils/ws-server.ts +6 -0
  34. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  35. package/dist/assets/main-C2JiGYnx.css +0 -1
@@ -37,7 +37,8 @@ import {
37
37
  type ToolInput,
38
38
  } from '@qwen-code/sdk';
39
39
  import type { EngineOutput, EngineModel } from '$shared/types/unified';
40
- import type { AIEngine, EngineQueryOptions } from '../../types';
40
+ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
41
+ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
41
42
  import { resolveOsPath } from '$backend/utils/paths';
42
43
  import { debug } from '$shared/utils/logger';
43
44
  import { getEngineEnv } from './environment';
@@ -345,6 +346,87 @@ export class QwenEngine implements AIEngine {
345
346
  }
346
347
  }
347
348
 
349
+ /**
350
+ * One-shot structured JSON generation via prompt engineering.
351
+ *
352
+ * The Qwen SDK has no native `outputSchema` / `response_format` option,
353
+ * so we instruct the model to emit JSON only, restrict tools with
354
+ * `coreTools: []`, and parse the final `result` text returned by the
355
+ * SDK's `SDKResultMessageSuccess`.
356
+ */
357
+ async generateStructured<T = unknown>(options: StructuredGenerationOptions): Promise<T> {
358
+ const {
359
+ prompt,
360
+ modelId,
361
+ schema,
362
+ projectPath,
363
+ abortController,
364
+ accountId,
365
+ } = options;
366
+
367
+ const resolution = getEngineEnv(accountId);
368
+ if (!resolution) {
369
+ throw new Error('Qwen Code is not configured. Add an API key in Settings → Engines → Qwen Code.');
370
+ }
371
+ const { env } = resolution;
372
+
373
+ const controller = abortController || new AbortController();
374
+ const resolvedProjectPath = resolveOsPath(projectPath);
375
+ const jsonPrompt = buildJsonPrompt(prompt, schema);
376
+
377
+ debug.log('engine', `[qwen structured] running with model=${modelId}`);
378
+
379
+ const sdkOptions: QueryOptions = {
380
+ cwd: resolvedProjectPath,
381
+ model: modelId,
382
+ env,
383
+ authType: 'openai',
384
+ abortController: controller,
385
+ includePartialMessages: false,
386
+ permissionMode: 'default',
387
+ coreTools: [],
388
+ maxSessionTurns: 1,
389
+ };
390
+
391
+ const sdkPrompt: SDKUserMessage = {
392
+ type: 'user',
393
+ uuid: crypto.randomUUID(),
394
+ session_id: '',
395
+ parent_tool_use_id: null,
396
+ message: { role: 'user', content: jsonPrompt },
397
+ };
398
+ const promptIterable = (async function* (): AsyncIterable<SDKUserMessage> {
399
+ yield sdkPrompt;
400
+ })();
401
+
402
+ const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
403
+
404
+ let resultText = '';
405
+ let errorMessage = '';
406
+ try {
407
+ for await (const message of queryInstance) {
408
+ if (message.type === 'result') {
409
+ if (message.subtype === 'success') {
410
+ resultText = message.result || '';
411
+ } else {
412
+ errorMessage = message.error?.message || message.subtype || 'unknown error';
413
+ }
414
+ }
415
+ }
416
+ } catch (error) {
417
+ if (controller.signal.aborted) {
418
+ throw new Error('Generation was cancelled');
419
+ }
420
+ throw error;
421
+ }
422
+
423
+ if (!resultText) {
424
+ throw new Error(errorMessage || 'Qwen returned no result text');
425
+ }
426
+
427
+ return extractJson<T>(resultText);
428
+ }
429
+
348
430
  resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
349
431
  const pending = this.pendingAskUserQuestion;
350
432
  if (!pending) {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Shared helpers for one-shot structured JSON generation.
3
+ *
4
+ * Engines whose SDKs lack a native JSON-schema output mode (OpenCode, Copilot,
5
+ * Qwen) fall back to prompt engineering: instruct the model to emit JSON only,
6
+ * then parse it out of whatever text the model returns. The native path on
7
+ * Claude and Codex doesn't need these helpers.
8
+ */
9
+
10
+ /** Wrap a user prompt with a JSON-only instruction and the target schema. */
11
+ export function buildJsonPrompt(prompt: string, schema: Record<string, unknown>): string {
12
+ return `${prompt}
13
+
14
+ IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text, no markdown fences, no commentary:
15
+ ${JSON.stringify(schema, null, 2)}`;
16
+ }
17
+
18
+ /**
19
+ * Extract a JSON object from a model response.
20
+ *
21
+ * Models routinely wrap JSON in markdown fences or prose even when asked
22
+ * not to. This searches in order:
23
+ * 1. ```json … ``` or ``` … ``` fenced block
24
+ * 2. The first balanced `{ … }` substring
25
+ * 3. The raw trimmed text
26
+ *
27
+ * Throws if nothing parses.
28
+ */
29
+ export function extractJson<T = unknown>(text: string): T {
30
+ const trimmed = text.trim();
31
+ if (!trimmed) {
32
+ throw new Error('Empty response — no JSON to parse');
33
+ }
34
+
35
+ const candidates: string[] = [];
36
+ const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/);
37
+ if (fenced) candidates.push(fenced[1].trim());
38
+
39
+ const braceStart = trimmed.indexOf('{');
40
+ const braceEnd = trimmed.lastIndexOf('}');
41
+ if (braceStart !== -1 && braceEnd > braceStart) {
42
+ candidates.push(trimmed.slice(braceStart, braceEnd + 1));
43
+ }
44
+
45
+ candidates.push(trimmed);
46
+
47
+ let lastError: unknown;
48
+ for (const candidate of candidates) {
49
+ try {
50
+ return JSON.parse(candidate) as T;
51
+ } catch (err) {
52
+ lastError = err;
53
+ }
54
+ }
55
+ throw new Error(
56
+ `Response did not contain valid JSON: ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` +
57
+ (lastError instanceof Error ? ` (${lastError.message})` : '')
58
+ );
59
+ }
@@ -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
+
@@ -246,14 +246,22 @@ export async function renameOperation(oldPath: string, newPath: string) {
246
246
  const normalizedNewPath = process.platform === 'win32' ?
247
247
  newPath.replace(/\//g, '\\') : newPath;
248
248
 
249
- const oldFile = Bun.file(normalizedOldPath);
250
- const newFile = Bun.file(normalizedNewPath);
251
-
252
- if (!(await oldFile.exists())) {
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 {
253
254
  throw new Error('Source path does not exist');
254
255
  }
255
256
 
256
- if (await newFile.exists()) {
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) {
257
265
  throw new Error('Destination path already exists');
258
266
  }
259
267
 
@@ -263,7 +271,7 @@ export async function renameOperation(oldPath: string, newPath: string) {
263
271
  }
264
272
 
265
273
  await rename(normalizedOldPath, normalizedNewPath);
266
- const stats = await newFile.stat();
274
+ const stats = await fsStat(normalizedNewPath);
267
275
 
268
276
  return {
269
277
  message: 'File/directory renamed successfully',
@@ -365,65 +373,10 @@ export async function duplicateOperation(sourcePath: string, targetPath: string)
365
373
  }
366
374
  }
367
375
 
368
- export async function uploadFileOperation(file: { name: string; type: string; size: number; data: Uint8Array } | any, targetPath: string) {
369
- if (!file || !file.name || !file.data) {
370
- throw new Error('File is required for upload');
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
- }
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.
427
380
 
428
381
  export async function deleteOperation(filePath: string, force: boolean = false) {
429
382
  if (!filePath) {
@@ -1,29 +1,85 @@
1
- import { describe, expect, test } from 'bun:test';
2
- import { validateFileSize } from './file-size-limit';
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
- // Default limit is 50MB
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
- const overLimit = (50 * 1024 * 1024) + 1; // 50MB + 1 byte
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(); // 1KB
18
- expect(() => validateFileSize(0)).not.toThrow(); // 0 bytes
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 limits on write and upload operations
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
- /** Default maximum file size: 50MB */
9
- export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
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 allowed limit.
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 MAX_FILE_SIZE
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
- if (size > MAX_FILE_SIZE) {
21
- const maxMB = MAX_FILE_SIZE / (1024 * 1024);
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
  }