agentgui 1.0.1117 → 1.0.1118
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/.gm/.embed-generation.code_chunks +1 -0
- package/.gm/.embed-generation.git_commit_vectors +1 -0
- package/.gm/.embed-generation.memories +1 -0
- package/.gm/.embed-generation.rssearch_vectors +1 -0
- package/.gm/prd.yml +15 -0
- package/AGENTS.md +1 -1
- package/lib/acp-sdk-manager.js +15 -2
- package/lib/claude-runner-agents.js +8 -1
- package/lib/http-handler.js +35 -566
- package/lib/http-routes/mutations.js +199 -0
- package/lib/http-routes/reads.js +212 -0
- package/lib/http-routes/shared.js +213 -0
- package/lib/ws-handlers/agents.js +137 -0
- package/lib/ws-handlers/chat.js +157 -0
- package/lib/ws-handlers/git.js +159 -0
- package/lib/ws-handlers/misc.js +36 -0
- package/lib/ws-handlers/shared.js +47 -0
- package/lib/ws-handlers/terminal-state.js +16 -0
- package/lib/ws-handlers-util.js +8 -526
- package/package.json +1 -1
- package/site/app/js/app.js +8 -103
- package/site/app/js/chat-persistence.js +123 -0
- package/site/app/vendor/anentrypoint-design/247420.css +1614 -488
- package/site/app/vendor/anentrypoint-design/247420.js +363 -77
- package/UX_OPTIMIZATION_SUMMARY.md +0 -238
- package/agentgui-after.png +0 -0
- package/agentgui-current.png +0 -0
- package/agentgui-final.png +0 -0
- package/agentgui-nobrand.png +0 -0
- package/agentgui-now.png +0 -0
- package/agentgui-v2.png +0 -0
- package/agentgui-v4.png +0 -0
- package/bash.exe.stackdump +0 -28
- package/design-reference.png +0 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import crypto from 'crypto';
|
|
4
|
+
import {
|
|
5
|
+
confineToRoots, fsAllowRoots, sanitizeEntryName, safeErrMsg, readBody,
|
|
6
|
+
isAllowRoot, moveToTrash, restoreFromTrash, SECRET_RE,
|
|
7
|
+
} from './shared.js';
|
|
8
|
+
|
|
9
|
+
// --- File mutations ----------------------------------------------------
|
|
10
|
+
// The Files surface is a real manager (fsbrowse-grade): rename, delete,
|
|
11
|
+
// mkdir, upload. Every route re-confines via confineToRoots (realpath, so
|
|
12
|
+
// a symlink inside a root cannot point a mutation outside it), refuses
|
|
13
|
+
// the roots themselves as targets, and sanitizes any NEW name to a single
|
|
14
|
+
// path component (sanitizeEntryName). All are POST/PUT-only with JSON or
|
|
15
|
+
// raw-byte bodies; errors map to plain machine codes the client renders
|
|
16
|
+
// as human copy.
|
|
17
|
+
|
|
18
|
+
// POST /api/rename {path, newName} -> {ok, path}
|
|
19
|
+
export async function handleRename(req, res, sendJSON) {
|
|
20
|
+
let body;
|
|
21
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
22
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
23
|
+
const allowRoots = fsAllowRoots();
|
|
24
|
+
const conf = confineToRoots(String(body.path || ''), allowRoots);
|
|
25
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
26
|
+
if (isAllowRoot(conf.realPath, allowRoots)) { sendJSON(req, res, 403, { error: 'forbidden: cannot rename an allowed root' }); return; }
|
|
27
|
+
const newName = sanitizeEntryName(body.newName);
|
|
28
|
+
if (!newName) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
29
|
+
if (SECRET_RE.test(newName)) { sendJSON(req, res, 403, { error: 'forbidden: secret/dotfile name' }); return; }
|
|
30
|
+
const target = path.join(path.dirname(conf.realPath), newName);
|
|
31
|
+
// The target stays in the same (already-confined) directory by
|
|
32
|
+
// construction, but re-check anyway so the invariant is local.
|
|
33
|
+
const tConf = confineToRoots(path.dirname(target), allowRoots);
|
|
34
|
+
if (!tConf.ok) { sendJSON(req, res, 403, { error: 'forbidden: target outside allowed roots' }); return; }
|
|
35
|
+
if (fs.existsSync(target)) { sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return; }
|
|
36
|
+
try { fs.renameSync(conf.realPath, target); sendJSON(req, res, 200, { ok: true, path: target }); }
|
|
37
|
+
catch (err) { sendJSON(req, res, err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400, { error: safeErrMsg(err) }); }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// POST /api/move {path, destDir, overwrite?} -> {ok, path}. Moves an
|
|
41
|
+
// entry into another directory; BOTH endpoints re-confine via realpath.
|
|
42
|
+
// Refuses: a root as the source, a directory moved into itself or its
|
|
43
|
+
// own subtree, and an existing target unless overwrite:true (and never
|
|
44
|
+
// overwrites a directory).
|
|
45
|
+
export async function handleMove(req, res, sendJSON) {
|
|
46
|
+
let body;
|
|
47
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
48
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
49
|
+
const allowRoots = fsAllowRoots();
|
|
50
|
+
const conf = confineToRoots(String(body.path || ''), allowRoots);
|
|
51
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
52
|
+
if (isAllowRoot(conf.realPath, allowRoots)) { sendJSON(req, res, 403, { error: 'forbidden: cannot move an allowed root' }); return; }
|
|
53
|
+
const dConf = confineToRoots(String(body.destDir || ''), allowRoots);
|
|
54
|
+
if (!dConf.ok) { sendJSON(req, res, dConf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + dConf.reason }); return; }
|
|
55
|
+
let destIsDir = false;
|
|
56
|
+
try { destIsDir = fs.statSync(dConf.realPath).isDirectory(); } catch {}
|
|
57
|
+
if (!destIsDir) { sendJSON(req, res, 400, { error: 'destination is not a directory' }); return; }
|
|
58
|
+
const name = sanitizeEntryName(path.basename(conf.realPath));
|
|
59
|
+
if (!name) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
60
|
+
// A directory must never move into itself or its own subtree.
|
|
61
|
+
const srcPrefix = conf.realPath + path.sep;
|
|
62
|
+
if (dConf.realPath === conf.realPath || dConf.realPath.startsWith(srcPrefix)) {
|
|
63
|
+
sendJSON(req, res, 400, { error: 'cannot move a folder into itself' }); return;
|
|
64
|
+
}
|
|
65
|
+
const target = path.join(dConf.realPath, name);
|
|
66
|
+
if (target === conf.realPath) { sendJSON(req, res, 200, { ok: true, path: target }); return; }
|
|
67
|
+
if (fs.existsSync(target)) {
|
|
68
|
+
let targetIsDir = false;
|
|
69
|
+
try { targetIsDir = fs.lstatSync(target).isDirectory(); } catch {}
|
|
70
|
+
if (targetIsDir || body.overwrite !== true) {
|
|
71
|
+
sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
try { fs.renameSync(conf.realPath, target); sendJSON(req, res, 200, { ok: true, path: target }); }
|
|
75
|
+
catch (err) {
|
|
76
|
+
const code = err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400;
|
|
77
|
+
sendJSON(req, res, code, { error: err.code === 'EXDEV' ? 'cannot move across drives' : err.message });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// POST /api/delete {path, recursive?} -> {ok}. Deleting a non-empty dir
|
|
82
|
+
// requires recursive:true (the client confirms first).
|
|
83
|
+
export async function handleDelete(req, res, sendJSON) {
|
|
84
|
+
let body;
|
|
85
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
86
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
87
|
+
const allowRoots = fsAllowRoots();
|
|
88
|
+
const conf = confineToRoots(String(body.path || ''), allowRoots);
|
|
89
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
90
|
+
if (isAllowRoot(conf.realPath, allowRoots)) { sendJSON(req, res, 403, { error: 'forbidden: cannot delete an allowed root' }); return; }
|
|
91
|
+
try {
|
|
92
|
+
const st = fs.lstatSync(conf.realPath);
|
|
93
|
+
// Soft-delete: move into a confined per-root .agentgui-trash/ instead
|
|
94
|
+
// of unlinking, so the only safety net isn't confirm-before (the
|
|
95
|
+
// pre-existing ConfirmDialog) but also undo-after, matching an
|
|
96
|
+
// fsbrowse-grade file manager. A non-empty directory without
|
|
97
|
+
// recursive=true still throws ENOTEMPTY BEFORE any move happens
|
|
98
|
+
// (checked via a dry probe) to keep that existing guard's semantics.
|
|
99
|
+
if (st.isDirectory() && body.recursive !== true) {
|
|
100
|
+
const dryEntries = fs.readdirSync(conf.realPath);
|
|
101
|
+
if (dryEntries.length) { sendJSON(req, res, 409, { error: 'directory is not empty' }); return; }
|
|
102
|
+
}
|
|
103
|
+
const trashInfo = moveToTrash(conf.realPath, allowRoots);
|
|
104
|
+
sendJSON(req, res, 200, { ok: true, trashId: trashInfo.trashId });
|
|
105
|
+
} catch (err) {
|
|
106
|
+
const code = err.code === 'ENOTEMPTY' ? 409 : (err.code === 'EACCES' || err.code === 'EPERM' ? 403 : (err.code === 'ENOENT' ? 404 : 400));
|
|
107
|
+
sendJSON(req, res, code, { error: err.code === 'ENOTEMPTY' ? 'directory is not empty' : err.message });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// POST /api/restore {trashId} -> {ok, path}. Undoes a /api/delete within
|
|
112
|
+
// its retention window (trashRetentionMs, default 10 minutes) by moving
|
|
113
|
+
// the entry back from .agentgui-trash/ to its original confined path.
|
|
114
|
+
export async function handleRestore(req, res, sendJSON) {
|
|
115
|
+
let body;
|
|
116
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
117
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
118
|
+
try {
|
|
119
|
+
const restored = restoreFromTrash(String(body.trashId || ''), fsAllowRoots());
|
|
120
|
+
sendJSON(req, res, 200, { ok: true, path: restored.path });
|
|
121
|
+
} catch (err) {
|
|
122
|
+
sendJSON(req, res, err.code === 'NOT_FOUND' ? 404 : (err.code === 'CONFLICT' ? 409 : 400), { error: err.message });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// POST /api/mkdir {dir, name} -> {ok, path}. dir must exist inside roots.
|
|
127
|
+
export async function handleMkdir(req, res, sendJSON) {
|
|
128
|
+
let body;
|
|
129
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
130
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
131
|
+
const allowRoots = fsAllowRoots();
|
|
132
|
+
const conf = confineToRoots(String(body.dir || ''), allowRoots);
|
|
133
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
134
|
+
const name = sanitizeEntryName(body.name);
|
|
135
|
+
if (!name) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
136
|
+
if (SECRET_RE.test(name)) { sendJSON(req, res, 403, { error: 'forbidden: secret/dotfile name' }); return; }
|
|
137
|
+
const target = path.join(conf.realPath, name);
|
|
138
|
+
if (fs.existsSync(target)) { sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return; }
|
|
139
|
+
try { fs.mkdirSync(target); sendJSON(req, res, 200, { ok: true, path: target }); }
|
|
140
|
+
catch (err) { sendJSON(req, res, err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400, { error: err.message }); }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// PUT /api/upload-file?dir=<enc>&name=<enc> with raw file bytes as the
|
|
144
|
+
// body (no multipart dependency; the client sends fetch(file)). 50MB cap,
|
|
145
|
+
// never overwrites unless ?overwrite=1. Distinct path from the legacy
|
|
146
|
+
// express-mounted /api/upload/:conversationId.
|
|
147
|
+
export async function handleUploadFile(req, res, sendJSON) {
|
|
148
|
+
let qs;
|
|
149
|
+
try { qs = new URL(req.url, 'http://localhost').searchParams; } catch { qs = new URLSearchParams(); }
|
|
150
|
+
// Require Content-Length header: rejects chunked or missing-length requests
|
|
151
|
+
// that could claim any size. Pre-validates the announced size before streaming.
|
|
152
|
+
const contentLength = req.headers['content-length'];
|
|
153
|
+
if (!contentLength) {
|
|
154
|
+
sendJSON(req, res, 411, { error: 'length required' }); return;
|
|
155
|
+
}
|
|
156
|
+
const MAX_UPLOAD = 50 * 1024 * 1024;
|
|
157
|
+
const len = parseInt(contentLength, 10);
|
|
158
|
+
if (isNaN(len) || len < 0 || len > MAX_UPLOAD) {
|
|
159
|
+
sendJSON(req, res, 413, { error: `file too large (max ${MAX_UPLOAD} bytes)` }); return;
|
|
160
|
+
}
|
|
161
|
+
const allowRoots = fsAllowRoots();
|
|
162
|
+
const conf = confineToRoots(qs.get('dir') || '', allowRoots);
|
|
163
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
164
|
+
const name = sanitizeEntryName(qs.get('name'));
|
|
165
|
+
if (!name) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
166
|
+
if (SECRET_RE.test(name)) { sendJSON(req, res, 403, { error: 'forbidden: secret/dotfile name' }); return; }
|
|
167
|
+
const target = path.join(conf.realPath, name);
|
|
168
|
+
if (fs.existsSync(target) && qs.get('overwrite') !== '1') { sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return; }
|
|
169
|
+
// Stream the upload body to a temp file to keep memory constant and
|
|
170
|
+
// avoid blocking the event loop with a large synchronous writeFileSync.
|
|
171
|
+
const tmpPath = target + '.tmp.' + crypto.randomBytes(6).toString('hex');
|
|
172
|
+
try {
|
|
173
|
+
await new Promise((resolve, reject) => {
|
|
174
|
+
const ws = fs.createWriteStream(tmpPath);
|
|
175
|
+
let total = 0;
|
|
176
|
+
ws.on('error', reject);
|
|
177
|
+
req.on('error', reject);
|
|
178
|
+
req.on('data', (chunk) => {
|
|
179
|
+
total += chunk.length;
|
|
180
|
+
if (total > MAX_UPLOAD) {
|
|
181
|
+
ws.destroy();
|
|
182
|
+
req.destroy();
|
|
183
|
+
const e = new Error('file too large (50MB cap)'); e.code = 'TOO_LARGE';
|
|
184
|
+
reject(e); return;
|
|
185
|
+
}
|
|
186
|
+
ws.write(chunk);
|
|
187
|
+
});
|
|
188
|
+
req.on('end', () => ws.end());
|
|
189
|
+
ws.on('finish', () => resolve(total));
|
|
190
|
+
});
|
|
191
|
+
fs.renameSync(tmpPath, target);
|
|
192
|
+
const uploadedSize = fs.statSync(target).size;
|
|
193
|
+
sendJSON(req, res, 200, { ok: true, path: target, size: uploadedSize });
|
|
194
|
+
} catch (err) {
|
|
195
|
+
try { fs.unlinkSync(tmpPath); } catch (_) {}
|
|
196
|
+
if (err.code === 'TOO_LARGE') { sendJSON(req, res, 413, { error: 'file too large (50MB cap)' }); return; }
|
|
197
|
+
sendJSON(req, res, err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400, { error: 'upload failed' });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import {
|
|
5
|
+
confineToRoots, fsAllowRoots, resolveConfinedPath, safeErrMsg, SECRET_RE,
|
|
6
|
+
} from './shared.js';
|
|
7
|
+
|
|
8
|
+
// Existence/shape probe for a proposed chat working directory, confined
|
|
9
|
+
// to the same allowlist as the Files surface (an unconfined stat would be
|
|
10
|
+
// a filesystem oracle). Returns {ok, dir} or a 403/404 with plain copy.
|
|
11
|
+
export function handleStat(req, res, routePath, sendJSON) {
|
|
12
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/stat');
|
|
13
|
+
const conf = confineToRoots(decodedPath, fsAllowRoots());
|
|
14
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: conf.reason }); return; }
|
|
15
|
+
try {
|
|
16
|
+
const st = fs.statSync(conf.realPath);
|
|
17
|
+
sendJSON(req, res, 200, { ok: true, dir: st.isDirectory(), path: conf.realPath });
|
|
18
|
+
} catch (err) {
|
|
19
|
+
sendJSON(req, res, err.code === 'ENOENT' ? 404 : 403, { error: safeErrMsg(err) });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Directory listing for the Files / folder-browser view (mirrors fsbrowse
|
|
24
|
+
// /api/list). Confined to an allowlist root exactly like /api/image - the
|
|
25
|
+
// normalize-then-prefix-check is the real guard (a `..` test after
|
|
26
|
+
// path.normalize is a no-op). Returns {path, segments, entries} so the kit
|
|
27
|
+
// FileGrid + BreadcrumbPath render directly. Allowed roots default to the
|
|
28
|
+
// server cwd + Claude projects dir; widen via FS_ROOTS (path-separated).
|
|
29
|
+
export function handleList(req, res, routePath, sendJSON) {
|
|
30
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'dir', '/api/list');
|
|
31
|
+
const allowRoots = fsAllowRoots();
|
|
32
|
+
// Empty path = the first allow-root (a sane default landing dir).
|
|
33
|
+
const reqPath = !decodedPath ? allowRoots[0] : decodedPath;
|
|
34
|
+
const conf = confineToRoots(reqPath, allowRoots);
|
|
35
|
+
if (!conf.ok) {
|
|
36
|
+
const code = conf.reason === 'not found' ? 404 : 403;
|
|
37
|
+
sendJSON(req, res, code, { error: 'forbidden: ' + conf.reason }); return;
|
|
38
|
+
}
|
|
39
|
+
// Use the symlink-resolved real path for all reads.
|
|
40
|
+
const normalizedPath = conf.realPath;
|
|
41
|
+
try {
|
|
42
|
+
const st = fs.statSync(normalizedPath);
|
|
43
|
+
if (!st.isDirectory()) { sendJSON(req, res, 400, { error: 'not a directory' }); return; }
|
|
44
|
+
// Classify by extension into the kit's data-file-type buckets so
|
|
45
|
+
// FileGrid renders the right rail/icon. dir/symlink come from stat.
|
|
46
|
+
const EXT_TYPE = {
|
|
47
|
+
image: ['png','jpg','jpeg','gif','webp','svg','bmp','ico','avif'],
|
|
48
|
+
video: ['mp4','webm','mov','mkv','avi','m4v'],
|
|
49
|
+
audio: ['mp3','wav','ogg','flac','m4a','aac'],
|
|
50
|
+
code: ['js','mjs','cjs','ts','tsx','jsx','rs','go','py','rb','java','c','cpp','h','hpp','cs','php','sh','css','html','json','yml','yaml','toml','sql'],
|
|
51
|
+
text: ['txt','md','log','csv','env'],
|
|
52
|
+
archive: ['zip','tar','gz','tgz','rar','7z','bz2','xz'],
|
|
53
|
+
document: ['pdf','doc','docx','xls','xlsx','ppt','pptx','odt'],
|
|
54
|
+
};
|
|
55
|
+
const typeFor = (name, dirent) => {
|
|
56
|
+
if (dirent.isSymbolicLink()) return 'symlink';
|
|
57
|
+
if (dirent.isDirectory()) return 'dir';
|
|
58
|
+
const ext = path.extname(name).slice(1).toLowerCase();
|
|
59
|
+
for (const [t, exts] of Object.entries(EXT_TYPE)) if (exts.includes(ext)) return t;
|
|
60
|
+
return 'other';
|
|
61
|
+
};
|
|
62
|
+
const dirents = fs.readdirSync(normalizedPath, { withFileTypes: true }).filter((d) => !SECRET_RE.test(d.name));
|
|
63
|
+
const entries = dirents.map((d) => {
|
|
64
|
+
const full = path.join(normalizedPath, d.name);
|
|
65
|
+
let size = null, modified = null, permissions;
|
|
66
|
+
try {
|
|
67
|
+
const s = fs.statSync(full); size = s.isDirectory() ? null : s.size; modified = s.mtime.toISOString();
|
|
68
|
+
// Per-entry permission probe (mirrors fsbrowse checkPermissions) so
|
|
69
|
+
// the row reads honestly (read-only / no access) instead of a silent
|
|
70
|
+
// size:null on a stat failure. A stat success means at least read.
|
|
71
|
+
const perms = ['read'];
|
|
72
|
+
try { fs.accessSync(full, fs.constants.W_OK); perms.push('write'); } catch (_) {}
|
|
73
|
+
permissions = perms;
|
|
74
|
+
} catch (e) {
|
|
75
|
+
// Could not stat (commonly EACCES): mark no-access so the client
|
|
76
|
+
// disables open + shows the tag, rather than failing silently.
|
|
77
|
+
permissions = e && e.code === 'EACCES' ? 'EACCES' : [];
|
|
78
|
+
}
|
|
79
|
+
return { name: d.name, type: typeFor(d.name, d), size, modified, path: full, permissions };
|
|
80
|
+
}).sort((a, b) => (a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) || a.name.localeCompare(b.name));
|
|
81
|
+
// Breadcrumb segments from the absolute path (drive/root aware).
|
|
82
|
+
const segments = normalizedPath.split(/[\\\/]+/).filter(Boolean);
|
|
83
|
+
sendJSON(req, res, 200, { path: normalizedPath, segments, entries, roots: allowRoots });
|
|
84
|
+
} catch (err) {
|
|
85
|
+
const code = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
|
|
86
|
+
sendJSON(req, res, code, { error: safeErrMsg(err) });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Raw file bytes for the Files preview pane. Confined to the SAME
|
|
91
|
+
// allowlist roots as /api/list (server cwd + Claude projects dir, widened
|
|
92
|
+
// via FS_ROOTS). Same normalize-then-prefix-check guard. Capped at 512KB
|
|
93
|
+
// and limited to reasonable text/code/image types so this is never a
|
|
94
|
+
// generic arbitrary-file reader. Images are served via /api/image; this
|
|
95
|
+
// returns text/* with utf-8.
|
|
96
|
+
export function handleFile(req, res, routePath) {
|
|
97
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/file/');
|
|
98
|
+
const allowRoots = fsAllowRoots();
|
|
99
|
+
const conf = confineToRoots(decodedPath, allowRoots);
|
|
100
|
+
if (!conf.ok) { res.writeHead(conf.reason === 'not found' ? 404 : 403); res.end('Forbidden'); return; }
|
|
101
|
+
const normalizedPath = conf.realPath;
|
|
102
|
+
// Block secret-bearing files regardless of root: dotfiles, env/key/cert
|
|
103
|
+
// material, and credential stores must never be readable through the
|
|
104
|
+
// Files preview even when they sit inside an allowed root.
|
|
105
|
+
const base = path.basename(normalizedPath);
|
|
106
|
+
if (SECRET_RE.test(base)) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
107
|
+
// Only known text/code extensions (images go through /api/image). An
|
|
108
|
+
// unknown/binary extension is rejected, never served as octet-stream.
|
|
109
|
+
// env/conf/cfg/ini are dropped - they commonly carry secrets.
|
|
110
|
+
const TEXT_EXTS = new Set([
|
|
111
|
+
'js','mjs','cjs','ts','tsx','jsx','rs','go','py','rb','java','c','cpp','h','hpp','cs','php','sh','css','html','json','yml','yaml','toml','sql',
|
|
112
|
+
'txt','md','log','csv','xml','gitignore','dockerfile','svg',
|
|
113
|
+
]);
|
|
114
|
+
const ext = path.extname(normalizedPath).slice(1).toLowerCase()
|
|
115
|
+
|| path.basename(normalizedPath).toLowerCase();
|
|
116
|
+
if (!TEXT_EXTS.has(ext)) { res.writeHead(403); res.end('Forbidden: unsupported type'); return; }
|
|
117
|
+
try {
|
|
118
|
+
const st = fs.statSync(normalizedPath);
|
|
119
|
+
if (!st.isFile()) { res.writeHead(400); res.end('Not a file'); return; }
|
|
120
|
+
const MAX = 512 * 1024;
|
|
121
|
+
const fd = fs.openSync(normalizedPath, 'r');
|
|
122
|
+
const len = Math.min(st.size, MAX);
|
|
123
|
+
const buf = Buffer.alloc(len);
|
|
124
|
+
fs.readSync(fd, buf, 0, len, 0);
|
|
125
|
+
fs.closeSync(fd);
|
|
126
|
+
res.writeHead(200, {
|
|
127
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
128
|
+
'Cache-Control': 'no-cache',
|
|
129
|
+
'X-File-Truncated': st.size > MAX ? '1' : '0',
|
|
130
|
+
});
|
|
131
|
+
res.end(buf);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
const code = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
|
|
134
|
+
res.writeHead(code); res.end(safeErrMsg(err));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Confined raw-bytes download (any type) with an attachment disposition,
|
|
139
|
+
// so the Files view can offer download on a row. Same allowlist + realpath
|
|
140
|
+
// confinement as /api/file and /api/image - never a generic file reader.
|
|
141
|
+
export function handleDownload(req, res, routePath) {
|
|
142
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/download/');
|
|
143
|
+
const allowRoots = fsAllowRoots();
|
|
144
|
+
const conf = confineToRoots(decodedPath, allowRoots);
|
|
145
|
+
if (!conf.ok) { res.writeHead(conf.reason === 'not found' ? 404 : 403); res.end('Forbidden'); return; }
|
|
146
|
+
const normalizedPath = conf.realPath;
|
|
147
|
+
// Same secret-name block as /api/file: a download must not exfiltrate
|
|
148
|
+
// .env/.pem/.key/credential material just because it streams bytes.
|
|
149
|
+
if (SECRET_RE.test(path.basename(normalizedPath))) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
150
|
+
try {
|
|
151
|
+
const st = fs.statSync(normalizedPath);
|
|
152
|
+
if (!st.isFile()) { res.writeHead(400); res.end('Not a file'); return; }
|
|
153
|
+
const MAX = 50 * 1024 * 1024; // 50MB cap so a download can't exhaust memory
|
|
154
|
+
if (st.size > MAX) { res.writeHead(413); res.end('File too large to download'); return; }
|
|
155
|
+
const base = path.basename(normalizedPath);
|
|
156
|
+
const asciiName = base.replace(/[\\"\r\n]/g, '').replace(/[^\x20-\x7e]/g, '_');
|
|
157
|
+
res.writeHead(200, {
|
|
158
|
+
'Content-Type': 'application/octet-stream',
|
|
159
|
+
'Content-Disposition': 'attachment; filename="' + asciiName + '"; filename*=UTF-8\'\'' + encodeURIComponent(base),
|
|
160
|
+
'Content-Length': String(st.size),
|
|
161
|
+
'Cache-Control': 'no-cache',
|
|
162
|
+
});
|
|
163
|
+
const rs = fs.createReadStream(normalizedPath);
|
|
164
|
+
rs.on('error', (streamErr) => { if (!res.writableEnded) res.destroy(streamErr); });
|
|
165
|
+
rs.pipe(res);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
const code = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
|
|
168
|
+
res.writeHead(code); res.end(safeErrMsg(err));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Confined image bytes with a content-type allowlist (SVG intentionally
|
|
173
|
+
// excluded - see inline comment below). Its own allowlist roots (Claude
|
|
174
|
+
// projects dir + IMAGE_ROOTS), distinct from fsAllowRoots(), because the
|
|
175
|
+
// user home is never a default root for arbitrary image reads.
|
|
176
|
+
export function handleImage(req, res, routePath, sendJSON) {
|
|
177
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/image/');
|
|
178
|
+
// Confine reads to an allowlist root. Without this the route is an
|
|
179
|
+
// arbitrary-file-read of any image-extensioned path on the host (the
|
|
180
|
+
// prior `includes('..')` guard is a no-op after path.normalize resolves
|
|
181
|
+
// the segments). Allowed roots: the Claude projects dir (history images)
|
|
182
|
+
// only; add more via IMAGE_ROOTS (path-separated). The user home is NOT
|
|
183
|
+
// a default root - it covers ~/.ssh, ~/.aws, dotfiles etc., so an image
|
|
184
|
+
// route reaching all of home is a broad read of anything image-shaped.
|
|
185
|
+
// confineToRoots also realpath-resolves so a symlink inside a root can't
|
|
186
|
+
// point an image read at an out-of-root file.
|
|
187
|
+
const allowRoots = [
|
|
188
|
+
process.env.CLAUDE_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects'),
|
|
189
|
+
...(process.env.IMAGE_ROOTS ? process.env.IMAGE_ROOTS.split(path.delimiter) : []),
|
|
190
|
+
].map(r => path.normalize(r));
|
|
191
|
+
const conf = confineToRoots(decodedPath, allowRoots);
|
|
192
|
+
if (!conf.ok) { res.writeHead(conf.reason === 'not found' ? 404 : 403); res.end(conf.reason === 'not found' ? 'Not found' : 'Forbidden'); return; }
|
|
193
|
+
const normalizedPath = conf.realPath;
|
|
194
|
+
try {
|
|
195
|
+
const ext = path.extname(normalizedPath).toLowerCase();
|
|
196
|
+
const mimeTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
|
|
197
|
+
// SVG is intentionally excluded: browsers render SVG as a live document
|
|
198
|
+
// in the app's origin, so an agent-written SVG with a <script src=CDN>
|
|
199
|
+
// would execute in the agentgui origin (CSP allows unpkg/jsdelivr).
|
|
200
|
+
// Files preview uses /api/file/download (attachment) for SVG.
|
|
201
|
+
const contentType = mimeTypes[ext];
|
|
202
|
+
if (!contentType) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
203
|
+
const imgSt = fs.statSync(normalizedPath);
|
|
204
|
+
const IMG_MAX = 20 * 1024 * 1024; // 20MB hard cap
|
|
205
|
+
if (imgSt.size > IMG_MAX) { res.writeHead(413); res.end('Image too large'); return; }
|
|
206
|
+
// Always stream to avoid blocking the event loop on large synchronous reads.
|
|
207
|
+
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-cache', 'Content-Length': String(imgSt.size) });
|
|
208
|
+
const imgRs = fs.createReadStream(normalizedPath);
|
|
209
|
+
imgRs.on('error', (streamErr) => { if (!res.writableEnded) res.destroy(streamErr); });
|
|
210
|
+
imgRs.pipe(res);
|
|
211
|
+
} catch (err) { sendJSON(req, res, 400, { error: 'cannot read image' }); }
|
|
212
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import crypto from 'crypto';
|
|
5
|
+
|
|
6
|
+
// Module-level platform constant — never changes at runtime.
|
|
7
|
+
export const IS_WINDOWS = os.platform() === 'win32';
|
|
8
|
+
|
|
9
|
+
// Confine a requested filesystem path to an allowlist of roots. Two layers:
|
|
10
|
+
// 1. normalize + resolved-prefix check on the LEXICAL path (blocks `../`
|
|
11
|
+
// traversal, which path.normalize collapses so a literal `..` test is a
|
|
12
|
+
// no-op);
|
|
13
|
+
// 2. fs.realpathSync + the SAME prefix check on the REAL path, so a symlink
|
|
14
|
+
// that lives inside an allowed root but points outside it cannot escape
|
|
15
|
+
// (the lexical path passes layer 1, the resolved target fails layer 2).
|
|
16
|
+
// Returns { ok, realPath, reason }. realPath is the symlink-resolved absolute
|
|
17
|
+
// path to stat/read; callers use it, never the raw input. A non-existent path
|
|
18
|
+
// has no realpath yet, so it fails closed with reason 'not found'.
|
|
19
|
+
export function confineToRoots(inputPath, allowRoots) {
|
|
20
|
+
const norms = allowRoots.map(r => path.normalize(r));
|
|
21
|
+
const expanded = inputPath && inputPath.startsWith('~') ? inputPath.replace('~', os.homedir()) : inputPath;
|
|
22
|
+
const normalizedPath = path.normalize(expanded || '');
|
|
23
|
+
const isAbsolute = IS_WINDOWS ? /^[A-Za-z]:[\\/]/.test(normalizedPath) : normalizedPath.startsWith('/');
|
|
24
|
+
const within = (p) => {
|
|
25
|
+
const np = IS_WINDOWS ? p.toLowerCase() : p;
|
|
26
|
+
return norms.some(root => {
|
|
27
|
+
const r = IS_WINDOWS ? root.toLowerCase() : root;
|
|
28
|
+
return np === r || np.startsWith(r + path.sep);
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
if (!isAbsolute || !within(normalizedPath)) return { ok: false, reason: 'path outside allowed roots' };
|
|
32
|
+
// realpath the target and re-confine, defeating symlink escape (TOCTOU/link
|
|
33
|
+
// traversal). If realpath throws (missing path / broken link) fail closed.
|
|
34
|
+
let realPath;
|
|
35
|
+
try { realPath = fs.realpathSync(normalizedPath); }
|
|
36
|
+
catch (e) { return { ok: false, reason: e && e.code === 'ENOENT' ? 'not found' : 'cannot resolve path', code: e && e.code }; }
|
|
37
|
+
if (!within(realPath)) return { ok: false, reason: 'symlink target outside allowed roots' };
|
|
38
|
+
return { ok: true, realPath };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Mask ?token=VALUE in a URL string before logging so credentials never
|
|
42
|
+
// appear in server logs or error messages.
|
|
43
|
+
export function maskToken(url) {
|
|
44
|
+
if (typeof url !== 'string') return url;
|
|
45
|
+
return url.replace(/([?&]token=)[^&]*/gi, '$1***');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Secret-bearing basenames that must never be readable through ANY confined
|
|
49
|
+
// raw-bytes route (preview or download), even when they sit inside an allowed
|
|
50
|
+
// root: dotfiles, env/key/cert material, and credential stores. One const so
|
|
51
|
+
// /api/file and /api/download can never drift apart.
|
|
52
|
+
export const SECRET_RE = /(^\.|\.(env|pem|key|crt|p12|pfx)$|secret|credential|\.npmrc$|\.netrc$)/i;
|
|
53
|
+
|
|
54
|
+
// The allowlist the Files surface operates within: server cwd + Claude
|
|
55
|
+
// projects dir, widened via FS_ROOTS (path-separated). One construction so
|
|
56
|
+
// /api/list,file,download and the mutation routes can never drift apart.
|
|
57
|
+
export function fsAllowRoots() {
|
|
58
|
+
const roots = [
|
|
59
|
+
process.env.CLAUDE_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects'),
|
|
60
|
+
];
|
|
61
|
+
// The server cwd is only exposed when PASSWORD is set (the witnessed
|
|
62
|
+
// localhost-PASSWORD deploy lists the repo tree) or FS_ALLOW_CWD=1 is opted
|
|
63
|
+
// in. An open no-PASSWORD deploy must NOT expose the whole server tree.
|
|
64
|
+
if (process.env.PASSWORD || process.env.FS_ALLOW_CWD === '1') {
|
|
65
|
+
roots.push(process.env.STARTUP_CWD || process.cwd());
|
|
66
|
+
}
|
|
67
|
+
if (process.env.FS_ROOTS) roots.push(...process.env.FS_ROOTS.split(path.delimiter));
|
|
68
|
+
return roots.map(r => path.normalize(r));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// A new file/dir name must be a single path component: no separators, no
|
|
72
|
+
// traversal, no NTFS alternate-data-stream colon, no reserved Windows device
|
|
73
|
+
// names, no trailing dot/space (Windows silently strips them, aliasing two
|
|
74
|
+
// names onto one entry). Returns the trimmed name or null when inadmissible.
|
|
75
|
+
export function sanitizeEntryName(name) {
|
|
76
|
+
if (typeof name !== 'string') return null;
|
|
77
|
+
const n = name.trim();
|
|
78
|
+
if (!n || n.length > 255) return null;
|
|
79
|
+
if (/[\\/:*?"<>|\x00-\x1f]/.test(n)) return null;
|
|
80
|
+
if (n === '.' || n === '..') return null;
|
|
81
|
+
if (/[. ]$/.test(n)) return null;
|
|
82
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(n)) return null;
|
|
83
|
+
return n;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Every confined filesystem route accepts its target path via a `?path=`/
|
|
87
|
+
// `?dir=` query param, preferred over a path SEGMENT. A reverse proxy's
|
|
88
|
+
// proxy_pass URI normalization can decode-then-reencode the request path,
|
|
89
|
+
// collapsing an encoded %2F segment slash back into a literal '/' before
|
|
90
|
+
// forwarding - the app then sees extra path segments instead of one opaque
|
|
91
|
+
// one, strips what it thinks is a leading '/', and silently turns an absolute
|
|
92
|
+
// path into a relative one that fails confinement even for genuinely
|
|
93
|
+
// accessible directories/files. A query param is untouched by that
|
|
94
|
+
// normalization on any proxy in front of this app. `legacyPrefix` is the old
|
|
95
|
+
// `/api/xxx/<path>` route prefix, still accepted for any caller not yet
|
|
96
|
+
// updated to the query-param form.
|
|
97
|
+
export function resolveConfinedPath(req, routePath, queryKey, legacyPrefix) {
|
|
98
|
+
const url = new URL(req.url, 'http://x');
|
|
99
|
+
const qVal = url.searchParams.get(queryKey);
|
|
100
|
+
if (qVal != null) return qVal;
|
|
101
|
+
const raw = routePath.split('?')[0].slice(legacyPrefix.length).replace(/^\//, '');
|
|
102
|
+
return raw ? decodeURIComponent(raw) : '';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Map a Node.js filesystem error code to a safe human-readable string that
|
|
106
|
+
// does not disclose host paths or internal stack context. Used everywhere an
|
|
107
|
+
// err.message would otherwise be returned to the client.
|
|
108
|
+
export function safeErrMsg(err) {
|
|
109
|
+
if (!err) return 'unknown error';
|
|
110
|
+
switch (err.code) {
|
|
111
|
+
case 'ENOENT': return 'file not found';
|
|
112
|
+
case 'EACCES': return 'permission denied';
|
|
113
|
+
case 'EPERM': return 'operation not permitted';
|
|
114
|
+
case 'EISDIR': return 'path is a directory';
|
|
115
|
+
case 'ENOTDIR': return 'path is not a directory';
|
|
116
|
+
case 'ENOTEMPTY': return 'directory is not empty';
|
|
117
|
+
case 'EEXIST': return 'file already exists';
|
|
118
|
+
case 'EXDEV': return 'cannot move across drives';
|
|
119
|
+
case 'EMFILE': return 'too many open files';
|
|
120
|
+
case 'ENOSPC': return 'no space left on device';
|
|
121
|
+
default: return 'operation failed';
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Read a request body with a hard size cap; resolves a Buffer or rejects with
|
|
126
|
+
// .code='TOO_LARGE' so the caller can answer 413 without buffering the rest.
|
|
127
|
+
export function readBody(req, maxBytes) {
|
|
128
|
+
return new Promise((resolve, reject) => {
|
|
129
|
+
const chunks = []; let total = 0;
|
|
130
|
+
req.on('data', (c) => {
|
|
131
|
+
total += c.length;
|
|
132
|
+
if (total > maxBytes) { const e = new Error('body too large'); e.code = 'TOO_LARGE'; req.destroy(); reject(e); return; }
|
|
133
|
+
chunks.push(c);
|
|
134
|
+
});
|
|
135
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
136
|
+
req.on('error', reject);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// True when the resolved path IS one of the allowlist roots - the roots
|
|
141
|
+
// themselves are never mutation targets (rename/delete of a root would orphan
|
|
142
|
+
// the whole surface).
|
|
143
|
+
export function isAllowRoot(realPath, allowRoots) {
|
|
144
|
+
const p = IS_WINDOWS ? realPath.toLowerCase() : realPath;
|
|
145
|
+
return allowRoots.some(r => (IS_WINDOWS ? r.toLowerCase() : r) === p);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// --- Soft-delete (trash) -----------------------------------------------
|
|
149
|
+
// /api/delete moves entries into <root>/.agentgui-trash/<trashId>__<name>
|
|
150
|
+
// instead of unlinking, giving a short undo window. In-memory index only
|
|
151
|
+
// (server restart forfeits the undo window - acceptable since the retention
|
|
152
|
+
// window itself is short and this is a convenience net on top of, not a
|
|
153
|
+
// replacement for, the pre-delete ConfirmDialog). Purged after
|
|
154
|
+
// TRASH_RETENTION_MS or when trashIndex grows past TRASH_MAX_ENTRIES
|
|
155
|
+
// (oldest-first), so a long-running server's trash dir can't grow unbounded.
|
|
156
|
+
const TRASH_DIR_NAME = '.agentgui-trash';
|
|
157
|
+
const TRASH_RETENTION_MS = parseInt(process.env.AGENTGUI_TRASH_RETENTION_MS || '', 10) || 10 * 60 * 1000;
|
|
158
|
+
const TRASH_MAX_ENTRIES = 200;
|
|
159
|
+
const trashIndex = new Map(); // trashId -> { trashPath, originalPath, root, deletedAt }
|
|
160
|
+
|
|
161
|
+
function purgeExpiredTrash() {
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
for (const [id, info] of trashIndex) {
|
|
164
|
+
if (now - info.deletedAt > TRASH_RETENTION_MS) {
|
|
165
|
+
try { fs.rmSync(info.trashPath, { recursive: true, force: true }); } catch { /* already gone */ }
|
|
166
|
+
trashIndex.delete(id);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (trashIndex.size > TRASH_MAX_ENTRIES) {
|
|
170
|
+
const sorted = [...trashIndex.entries()].sort((a, b) => a[1].deletedAt - b[1].deletedAt);
|
|
171
|
+
for (const [id, info] of sorted.slice(0, trashIndex.size - TRASH_MAX_ENTRIES)) {
|
|
172
|
+
try { fs.rmSync(info.trashPath, { recursive: true, force: true }); } catch {}
|
|
173
|
+
trashIndex.delete(id);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Which allowed root a confined realPath lives under - the trash dir sits
|
|
179
|
+
// alongside it (still inside the SAME root, so confineToRoots covers the
|
|
180
|
+
// trash path too - no new unconfined surface).
|
|
181
|
+
function rootFor(realPath, allowRoots) {
|
|
182
|
+
const p = IS_WINDOWS ? realPath.toLowerCase() : realPath;
|
|
183
|
+
return allowRoots.find(r => { const rr = IS_WINDOWS ? r.toLowerCase() : r; return p === rr || p.startsWith(rr + path.sep); });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function moveToTrash(realPath, allowRoots) {
|
|
187
|
+
purgeExpiredTrash();
|
|
188
|
+
const root = rootFor(realPath, allowRoots);
|
|
189
|
+
if (!root) { const e = new Error('not confined to an allowed root'); e.code = 'EACCES'; throw e; }
|
|
190
|
+
const trashDir = path.join(root, TRASH_DIR_NAME);
|
|
191
|
+
fs.mkdirSync(trashDir, { recursive: true });
|
|
192
|
+
const trashId = crypto.randomBytes(8).toString('hex');
|
|
193
|
+
const base = path.basename(realPath);
|
|
194
|
+
const trashPath = path.join(trashDir, trashId + '__' + base);
|
|
195
|
+
fs.renameSync(realPath, trashPath);
|
|
196
|
+
trashIndex.set(trashId, { trashPath, originalPath: realPath, root, deletedAt: Date.now() });
|
|
197
|
+
return { trashId };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function restoreFromTrash(trashId, allowRoots) {
|
|
201
|
+
const info = trashIndex.get(trashId);
|
|
202
|
+
if (!info) { const e = new Error('nothing to restore - the undo window has expired or this was already restored'); e.code = 'NOT_FOUND'; throw e; }
|
|
203
|
+
// Re-confine the ORIGINAL path at restore time (not trust the cached one
|
|
204
|
+
// blindly) - the allowlist itself doesn't change at runtime, but this keeps
|
|
205
|
+
// restore honoring the exact same confinement contract every other route does.
|
|
206
|
+
const conf = confineToRoots(info.originalPath, allowRoots);
|
|
207
|
+
if (!conf.ok && conf.reason !== 'not found') { const e = new Error('restore target is no longer inside an accessible folder'); e.code = 'CONFLICT'; throw e; }
|
|
208
|
+
if (fs.existsSync(info.originalPath)) { const e = new Error('a file already exists at the original location'); e.code = 'CONFLICT'; throw e; }
|
|
209
|
+
fs.mkdirSync(path.dirname(info.originalPath), { recursive: true });
|
|
210
|
+
fs.renameSync(info.trashPath, info.originalPath);
|
|
211
|
+
trashIndex.delete(trashId);
|
|
212
|
+
return { path: info.originalPath };
|
|
213
|
+
}
|