pi-web-ui 0.88.0 → 0.90.0
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/CHANGELOG.md +80 -1
- package/dist/server/agent-service.js +464 -68
- package/dist/server/attachments.js +39 -0
- package/dist/server/auth-cookie.js +23 -0
- package/dist/server/client-state.js +35 -0
- package/dist/server/composer-drafts.js +20 -2
- package/dist/server/conversation-read-tool.js +325 -0
- package/dist/server/dsh/dsh-agent-service.js +46 -11
- package/dist/server/file-archives.js +258 -0
- package/dist/server/file-transfer-routes.js +113 -0
- package/dist/server/files-service.js +123 -1
- package/dist/server/index.js +361 -14
- package/dist/server/marker-service.js +3 -1
- package/dist/server/model-admin.js +285 -36
- package/dist/server/plugins.js +152 -5
- package/dist/server/queue-utils.js +16 -0
- package/dist/server/schedule-agent-tool.js +240 -0
- package/dist/server/scheduler-tasks.js +414 -0
- package/dist/server/settings-service.js +76 -2
- package/dist/server/terminals.js +14 -1
- package/dist/server/tool-manager.js +16 -1
- package/dist/server/update-check.js +253 -19
- package/dist/server/webui-context.js +4 -0
- package/dist/server/ws-unknown-types.js +44 -0
- package/extensions/webui.ts +9 -2
- package/package.json +7 -3
- package/plugin-sdk/index.d.ts +4 -0
- package/plugin-sdk/index.mjs +9 -0
- package/plugins/catalog.json +11 -2
- package/web/dist/assets/TerminalPanel-BDbdLhpT.js +6 -0
- package/web/dist/assets/index-1f_DP8S3.js +380 -0
- package/web/dist/assets/index-DeUwDA-C.css +10 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/TerminalPanel-CDH27dNP.js +0 -6
- package/web/dist/assets/index-CQg5A74_.js +0 -375
- package/web/dist/assets/index-DTEcxHWs.css +0 -10
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { createReadStream, createWriteStream, constants } from "node:fs";
|
|
2
|
+
import { copyFile, lstat, mkdir, mkdtemp, open, readdir, realpath, rm } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { pipeline } from "node:stream/promises";
|
|
6
|
+
import { Transform } from "node:stream";
|
|
7
|
+
import { createGunzip } from "node:zlib";
|
|
8
|
+
import * as tar from "tar";
|
|
9
|
+
import * as yauzl from "yauzl";
|
|
10
|
+
const MAX_ENTRIES = 20_000;
|
|
11
|
+
const MAX_BYTES = 1024 * 1024 * 1024;
|
|
12
|
+
export function archiveName(path, directory, now = new Date()) {
|
|
13
|
+
const time = now.toISOString().replace(/[:.]/g, "-");
|
|
14
|
+
return `${basename(path)}${directory ? `-${time}` : ""}.tar.gz`;
|
|
15
|
+
}
|
|
16
|
+
/** Archive and upload paths are always relative, portable paths, never machine paths. */
|
|
17
|
+
export function safeEntryPath(name) {
|
|
18
|
+
const parts = name
|
|
19
|
+
.replace(/\\/g, "/")
|
|
20
|
+
.replace(/^(\.\/)+/, "")
|
|
21
|
+
.replace(/\/$/, "")
|
|
22
|
+
.split("/");
|
|
23
|
+
if (name.length > 4096 ||
|
|
24
|
+
parts.length > 128 ||
|
|
25
|
+
!parts.length ||
|
|
26
|
+
parts.some((p) => !p ||
|
|
27
|
+
p === "." ||
|
|
28
|
+
p === ".." ||
|
|
29
|
+
/[\x00-\x1f<>:"|?*]/.test(p) ||
|
|
30
|
+
/[. ]$/.test(p) ||
|
|
31
|
+
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p))) {
|
|
32
|
+
throw new Error(`Unsafe entry path: ${name}`);
|
|
33
|
+
}
|
|
34
|
+
return parts.join("/");
|
|
35
|
+
}
|
|
36
|
+
/** Count implicit parent directories too, so deep paths cannot bypass the entry limit. */
|
|
37
|
+
function trackEntry(paths, name) {
|
|
38
|
+
let prefix = "";
|
|
39
|
+
for (const part of name.split("/")) {
|
|
40
|
+
prefix = prefix ? `${prefix}/${part}` : part;
|
|
41
|
+
paths.add(prefix.toLowerCase());
|
|
42
|
+
if (paths.size > MAX_ENTRIES)
|
|
43
|
+
throw new Error("Archive exceeds 20,000 expanded entries");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function maybeStat(path) {
|
|
47
|
+
try {
|
|
48
|
+
return await lstat(path);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
if (e.code === "ENOENT")
|
|
52
|
+
return null;
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Refuse symlinks in the destination, including existing parent directories. */
|
|
57
|
+
export async function safeDestination(root, name) {
|
|
58
|
+
let path = root;
|
|
59
|
+
for (const part of safeEntryPath(name).split("/")) {
|
|
60
|
+
path = join(path, part);
|
|
61
|
+
const st = await maybeStat(path);
|
|
62
|
+
if (st?.isSymbolicLink())
|
|
63
|
+
throw new Error(`Symbolic link destination: ${name}`);
|
|
64
|
+
}
|
|
65
|
+
return path;
|
|
66
|
+
}
|
|
67
|
+
function byteLimit() {
|
|
68
|
+
let bytes = 0;
|
|
69
|
+
return new Transform({
|
|
70
|
+
transform(chunk, _encoding, done) {
|
|
71
|
+
bytes += chunk.length;
|
|
72
|
+
done(bytes > MAX_BYTES ? new Error("Archive exceeds 1 GiB expanded size") : null, chunk);
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export async function createArchive(source, outputDir) {
|
|
77
|
+
const abs = resolve(source);
|
|
78
|
+
const st = await lstat(abs);
|
|
79
|
+
if ((!st.isFile() && !st.isDirectory()) || dirname(abs) === abs)
|
|
80
|
+
throw new Error("Select a regular file or folder, not a filesystem root");
|
|
81
|
+
const name = archiveName(abs, st.isDirectory());
|
|
82
|
+
const dest = join(outputDir ?? dirname(abs), name);
|
|
83
|
+
let entries = 0;
|
|
84
|
+
let bytes = 0;
|
|
85
|
+
// Enumerate before creating the output: never include the archive itself.
|
|
86
|
+
const names = [];
|
|
87
|
+
const inodes = new Set();
|
|
88
|
+
async function walk(path, name) {
|
|
89
|
+
const info = await lstat(path);
|
|
90
|
+
if (!info.isFile() && !info.isDirectory())
|
|
91
|
+
throw new Error("Archive source contains a link or special file");
|
|
92
|
+
if (info.isFile() && info.nlink > 1) {
|
|
93
|
+
const inode = `${info.dev}:${info.ino}`;
|
|
94
|
+
if (inodes.has(inode))
|
|
95
|
+
throw new Error("Archive source contains hard links");
|
|
96
|
+
inodes.add(inode);
|
|
97
|
+
}
|
|
98
|
+
if (++entries > MAX_ENTRIES || (bytes += info.size) > MAX_BYTES)
|
|
99
|
+
throw new Error("Archive limit exceeded (20,000 entries / 1 GiB)");
|
|
100
|
+
names.push(safeEntryPath(name));
|
|
101
|
+
if (info.isDirectory())
|
|
102
|
+
for (const child of await readdir(path))
|
|
103
|
+
await walk(join(path, child), `${name}/${child}`);
|
|
104
|
+
}
|
|
105
|
+
await walk(abs, basename(abs));
|
|
106
|
+
// Exclusive creation: never truncate an existing archive.
|
|
107
|
+
const handle = await open(dest, "wx", 0o600);
|
|
108
|
+
try {
|
|
109
|
+
const stream = tar.c({ gzip: true, cwd: dirname(abs), portable: true, strict: true, noDirRecurse: true }, names);
|
|
110
|
+
await pipeline(stream, handle.createWriteStream());
|
|
111
|
+
return { path: dest, name };
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
await handle.close().catch(() => { });
|
|
115
|
+
await rm(dest, { force: true });
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async function unzip(source, stage) {
|
|
120
|
+
const zip = await new Promise((ok, fail) => yauzl.open(source, { lazyEntries: true, strictFileNames: true }, (err, z) => (err ? fail(err) : ok(z))));
|
|
121
|
+
let count = 0;
|
|
122
|
+
let bytes = 0;
|
|
123
|
+
const paths = new Set();
|
|
124
|
+
await new Promise((ok, fail) => {
|
|
125
|
+
const abort = (err) => {
|
|
126
|
+
zip.close();
|
|
127
|
+
fail(err);
|
|
128
|
+
};
|
|
129
|
+
zip.on("error", abort);
|
|
130
|
+
zip.on("end", ok);
|
|
131
|
+
zip.on("entry", (entry) => {
|
|
132
|
+
void (async () => {
|
|
133
|
+
const name = safeEntryPath(entry.fileName);
|
|
134
|
+
trackEntry(paths, name);
|
|
135
|
+
const type = (entry.externalFileAttributes >>> 16) & 0o170000;
|
|
136
|
+
if (type && type !== 0o100000 && type !== 0o040000)
|
|
137
|
+
throw new Error("Archive contains a link or special file");
|
|
138
|
+
if (++count > MAX_ENTRIES || (bytes += entry.uncompressedSize) > MAX_BYTES)
|
|
139
|
+
throw new Error("Archive limit exceeded (20,000 entries / 1 GiB)");
|
|
140
|
+
const dest = join(stage, name);
|
|
141
|
+
if (entry.fileName.endsWith("/"))
|
|
142
|
+
await mkdir(dest, { recursive: true });
|
|
143
|
+
else {
|
|
144
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
145
|
+
const stream = await new Promise((resolveStream, reject) => zip.openReadStream(entry, (err, s) => (err ? reject(err) : resolveStream(s))));
|
|
146
|
+
await pipeline(stream, byteLimit(), createWriteStream(dest, { flags: "wx", mode: 0o600 }));
|
|
147
|
+
}
|
|
148
|
+
zip.readEntry();
|
|
149
|
+
})().catch(abort);
|
|
150
|
+
});
|
|
151
|
+
zip.readEntry();
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
async function unpack(source, stage) {
|
|
155
|
+
if (/\.zip$/i.test(source))
|
|
156
|
+
return unzip(source, stage);
|
|
157
|
+
if (/\.(?:tar|tar\.gz|tgz)$/i.test(source)) {
|
|
158
|
+
let count = 0;
|
|
159
|
+
let bytes = 0;
|
|
160
|
+
// Validate all headers before extracting anything, even into the private staging directory.
|
|
161
|
+
const seen = new Set();
|
|
162
|
+
const paths = new Set();
|
|
163
|
+
const parser = tar.t({
|
|
164
|
+
strict: true,
|
|
165
|
+
onReadEntry: (entry) => {
|
|
166
|
+
try {
|
|
167
|
+
if (entry.type === "Directory" && /^(\.\/)*\.?$/.test(entry.path))
|
|
168
|
+
return;
|
|
169
|
+
const name = safeEntryPath(entry.path).toLowerCase();
|
|
170
|
+
trackEntry(paths, name);
|
|
171
|
+
if (seen.has(name))
|
|
172
|
+
throw new Error(`Duplicate archive entry: ${name}`);
|
|
173
|
+
seen.add(name);
|
|
174
|
+
if (entry.type !== "File" && entry.type !== "Directory")
|
|
175
|
+
throw new Error("Archive contains a link or special file");
|
|
176
|
+
if (++count > MAX_ENTRIES || (bytes += entry.size) > MAX_BYTES)
|
|
177
|
+
throw new Error("Archive limit exceeded (20,000 entries / 1 GiB)");
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
parser.abort(err instanceof Error ? err : new Error(String(err)));
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
const input = createReadStream(source);
|
|
185
|
+
if (/\.(tgz|gz)$/i.test(source))
|
|
186
|
+
await pipeline(input, createGunzip(), byteLimit(), parser);
|
|
187
|
+
else
|
|
188
|
+
await pipeline(input, byteLimit(), parser);
|
|
189
|
+
await tar.x({ file: source, cwd: stage, strict: true, preservePaths: false, noChmod: true, noMtime: true });
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (/\.gz$/i.test(source)) {
|
|
193
|
+
const name = safeEntryPath(basename(source).slice(0, -3));
|
|
194
|
+
await pipeline(createReadStream(source), createGunzip(), byteLimit(), createWriteStream(join(stage, name), { flags: "wx", mode: 0o600 }));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
throw new Error("Supported archives: ZIP, TAR, TAR.GZ, TGZ, GZ");
|
|
198
|
+
}
|
|
199
|
+
export async function extractArchive(source, destination, policy) {
|
|
200
|
+
if (!["skip", "overwrite", "error"].includes(policy))
|
|
201
|
+
throw new Error("Invalid conflict policy");
|
|
202
|
+
const root = await realpath(destination);
|
|
203
|
+
if (!(await lstat(root)).isDirectory())
|
|
204
|
+
throw new Error("Destination must be a directory");
|
|
205
|
+
const canonicalSource = await realpath(source);
|
|
206
|
+
const sourceStat = await lstat(source);
|
|
207
|
+
if (!sourceStat.isFile() || sourceStat.size > MAX_BYTES)
|
|
208
|
+
throw new Error("Select an archive file no larger than 1 GiB");
|
|
209
|
+
const tmp = await mkdtemp(join(tmpdir(), "pi-web-extract-"));
|
|
210
|
+
try {
|
|
211
|
+
const snapshot = join(tmp, basename(source));
|
|
212
|
+
await copyFile(source, snapshot, constants.COPYFILE_EXCL);
|
|
213
|
+
const stage = join(tmp, "contents");
|
|
214
|
+
await mkdir(stage);
|
|
215
|
+
await unpack(snapshot, stage);
|
|
216
|
+
const plan = [];
|
|
217
|
+
async function walk(dir, prefix = "") {
|
|
218
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
219
|
+
const name = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
220
|
+
const dest = await safeDestination(root, name);
|
|
221
|
+
const existing = await maybeStat(dest);
|
|
222
|
+
const isDir = entry.isDirectory();
|
|
223
|
+
if (existing && existing.isDirectory() !== isDir)
|
|
224
|
+
throw new Error(`File/directory conflict: ${name}`);
|
|
225
|
+
if (existing && !isDir && policy === "error")
|
|
226
|
+
throw new Error(`File already exists: ${name}`);
|
|
227
|
+
if (resolve(dest) === canonicalSource)
|
|
228
|
+
throw new Error("Archive would overwrite itself");
|
|
229
|
+
plan.push({ src: join(dir, entry.name), dest, dir: isDir, exists: Boolean(existing) });
|
|
230
|
+
if (isDir)
|
|
231
|
+
await walk(join(dir, entry.name), name);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
await walk(stage);
|
|
235
|
+
let written = 0, skipped = 0;
|
|
236
|
+
for (const item of plan) {
|
|
237
|
+
await safeDestination(root, item.dest
|
|
238
|
+
.slice(root.length + (root.endsWith(sep) ? 0 : 1))
|
|
239
|
+
.split(sep)
|
|
240
|
+
.join("/"));
|
|
241
|
+
if (item.dir)
|
|
242
|
+
await mkdir(item.dest, { recursive: true });
|
|
243
|
+
else if (item.exists && policy === "skip")
|
|
244
|
+
skipped++;
|
|
245
|
+
else {
|
|
246
|
+
// Unlink instead of truncating: existing hardlinks must not change another file.
|
|
247
|
+
if (policy === "overwrite")
|
|
248
|
+
await rm(item.dest, { force: true });
|
|
249
|
+
await copyFile(item.src, item.dest, constants.COPYFILE_EXCL);
|
|
250
|
+
written++;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return { written, skipped };
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
await rm(tmp, { recursive: true, force: true });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import express, {} from "express";
|
|
2
|
+
import { mkdtemp, mkdir, open, realpath, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { join, dirname } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { createArchive, extractArchive, safeDestination, safeEntryPath } from "./file-archives.js";
|
|
6
|
+
import { isAbsoluteWirePath, wireToAbs, workspacePath } from "./files-service.js";
|
|
7
|
+
/** Registered behind the host's authentication middleware; shared by Pi and DSH. */
|
|
8
|
+
export function registerFileTransferRoutes(app, getCwd, temporaryRoot = tmpdir()) {
|
|
9
|
+
const busy = new Set();
|
|
10
|
+
function root(req) {
|
|
11
|
+
const id = typeof req.query.clientId === "string" ? req.query.clientId : "";
|
|
12
|
+
const cwd = getCwd(id);
|
|
13
|
+
if (!cwd)
|
|
14
|
+
throw new Error("Client is not connected; reconnect before transferring files");
|
|
15
|
+
return cwd;
|
|
16
|
+
}
|
|
17
|
+
function path(cwd, raw) {
|
|
18
|
+
if (typeof raw !== "string" || raw === "@root")
|
|
19
|
+
throw new Error("Invalid path");
|
|
20
|
+
if (isAbsoluteWirePath(raw))
|
|
21
|
+
return wireToAbs(raw);
|
|
22
|
+
const resolved = workspacePath(cwd, raw);
|
|
23
|
+
if (!resolved)
|
|
24
|
+
throw new Error("Path outside workspace");
|
|
25
|
+
return resolved.abs;
|
|
26
|
+
}
|
|
27
|
+
// A cross-origin form cannot set this header. No CORS permission is granted.
|
|
28
|
+
app.use("/api/file-transfer", (req, res, next) => {
|
|
29
|
+
if (req.headers["x-file-operation"] !== "1") {
|
|
30
|
+
res.status(403).send("Missing file operation header");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
next();
|
|
34
|
+
});
|
|
35
|
+
app.post("/api/file-transfer/archive", async (req, res) => {
|
|
36
|
+
let cwd;
|
|
37
|
+
let acquired = false;
|
|
38
|
+
let temp;
|
|
39
|
+
try {
|
|
40
|
+
cwd = root(req);
|
|
41
|
+
if (busy.has(cwd)) {
|
|
42
|
+
res.status(409).send("Another file operation is running");
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
busy.add(cwd);
|
|
46
|
+
acquired = true;
|
|
47
|
+
const source = path(cwd, req.body?.path);
|
|
48
|
+
if (req.body?.action === "extract") {
|
|
49
|
+
const result = await extractArchive(source, path(cwd, req.body.destination), req.body.policy);
|
|
50
|
+
res.json(result);
|
|
51
|
+
}
|
|
52
|
+
else if (req.body?.action === "compress" || req.body?.action === "download") {
|
|
53
|
+
if (req.body.action === "download")
|
|
54
|
+
temp = await mkdtemp(join(temporaryRoot, "pi-web-download-"));
|
|
55
|
+
const archive = await createArchive(source, temp);
|
|
56
|
+
if (temp) {
|
|
57
|
+
if (res.destroyed)
|
|
58
|
+
throw new Error("Download cancelled");
|
|
59
|
+
if ((await stat(archive.path)).size > 200 * 1024 * 1024)
|
|
60
|
+
throw new Error("Temporary download exceeds 200 MiB; compress in place and download the archive instead");
|
|
61
|
+
// The callback runs on completion AND disconnect. Never expose a reusable temp URL.
|
|
62
|
+
await new Promise((ok, fail) => res.download(archive.path, archive.name, (err) => (err ? fail(err) : ok())));
|
|
63
|
+
}
|
|
64
|
+
else
|
|
65
|
+
res.json({ name: archive.name });
|
|
66
|
+
}
|
|
67
|
+
else
|
|
68
|
+
throw new Error("Invalid archive action");
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
if (!res.headersSent && !res.destroyed)
|
|
72
|
+
res.status(400).send(err instanceof Error ? err.message : String(err));
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
if (temp)
|
|
76
|
+
await rm(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }).catch((err) => console.error("Temporary archive cleanup failed:", err));
|
|
77
|
+
if (acquired && cwd)
|
|
78
|
+
busy.delete(cwd);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
// One binary file per request, sequentially sent by the browser. Avoid base64 and WS message limits.
|
|
82
|
+
app.post("/api/file-transfer/upload", express.raw({ type: "application/octet-stream", limit: "32mb" }), async (req, res) => {
|
|
83
|
+
try {
|
|
84
|
+
const cwd = root(req);
|
|
85
|
+
const dir = await realpath(path(cwd, req.query.dir));
|
|
86
|
+
const name = safeEntryPath(typeof req.query.name === "string" ? req.query.name : "");
|
|
87
|
+
const dest = await safeDestination(dir, name);
|
|
88
|
+
if (!Buffer.isBuffer(req.body))
|
|
89
|
+
throw new Error("Expected a binary file");
|
|
90
|
+
if (req.query.kind === "directory") {
|
|
91
|
+
if (req.body.length)
|
|
92
|
+
throw new Error("Directory requests cannot contain file data");
|
|
93
|
+
await mkdir(dest, { recursive: true });
|
|
94
|
+
res.json({ name });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
98
|
+
const handle = await open(dest, "wx", 0o600); // Folder uploads never silently overwrite existing data.
|
|
99
|
+
try {
|
|
100
|
+
await handle.writeFile(req.body);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
await handle.close();
|
|
104
|
+
}
|
|
105
|
+
res.json({ name });
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
res
|
|
109
|
+
.status(err.code === "EEXIST" ? 409 : 400)
|
|
110
|
+
.send(err instanceof Error ? err.message : String(err));
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
}
|
|
@@ -86,7 +86,16 @@ export function absoluteParent(wire) {
|
|
|
86
86
|
/** 预览只读文件前 512KB。 */
|
|
87
87
|
export const MAX_PREVIEW_BYTES = 512 * 1024;
|
|
88
88
|
/** 右键上传单文件上限(内存中转 base64 → Buffer)。 */
|
|
89
|
-
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
89
|
+
export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
90
|
+
/** 上传 cap 对应的 base64 文本长度上限(4/3 膨胀,向上取整到 4 字符边界)。 */
|
|
91
|
+
export const MAX_UPLOAD_BASE64_CHARS = Math.ceil(MAX_UPLOAD_BYTES / 3) * 4;
|
|
92
|
+
/** WS 入站帧上限:base64 上限 + 1MB JSON 包络余量(dirPath/name/type)。
|
|
93
|
+
* server/index.ts 的 maxPayload 由此取值,两处上限保持对齐。 */
|
|
94
|
+
export const WS_MAX_PAYLOAD_BYTES = MAX_UPLOAD_BASE64_CHARS + 1024 * 1024;
|
|
95
|
+
/** base64 文本长度是否必定超 cap(解码前快拒,不分配 Buffer)。 */
|
|
96
|
+
export function isUploadDataTooLong(dataLength, capBytes = MAX_UPLOAD_BYTES) {
|
|
97
|
+
return dataLength > Math.ceil(capBytes / 3) * 4;
|
|
98
|
+
}
|
|
90
99
|
// mac/linux: hide build & dependency noise (original behavior).
|
|
91
100
|
const IGNORED_ENTRIES = new Set([
|
|
92
101
|
"node_modules",
|
|
@@ -878,6 +887,10 @@ export class FilesService {
|
|
|
878
887
|
}
|
|
879
888
|
uploadRel = rawRel.split(sep).join("/");
|
|
880
889
|
}
|
|
890
|
+
if (isUploadDataTooLong(data.length)) {
|
|
891
|
+
emitErr(`文件过大:${name}(上限 ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
881
894
|
const buf = Buffer.from(data, "base64");
|
|
882
895
|
if (buf.length === 0) {
|
|
883
896
|
emitErr(`空文件:${name}`, `Empty file: ${name}`);
|
|
@@ -939,6 +952,7 @@ export class FilesService {
|
|
|
939
952
|
text: `已创建文件夹:${abs}`,
|
|
940
953
|
textEn: `Folder created: ${abs}`,
|
|
941
954
|
});
|
|
955
|
+
return abs;
|
|
942
956
|
}
|
|
943
957
|
catch (err) {
|
|
944
958
|
this.host.emit({
|
|
@@ -947,6 +961,7 @@ export class FilesService {
|
|
|
947
961
|
text: `创建文件夹失败:${err.message}`,
|
|
948
962
|
textEn: `Failed to create folder: ${err.message}`,
|
|
949
963
|
});
|
|
964
|
+
return null;
|
|
950
965
|
}
|
|
951
966
|
}
|
|
952
967
|
/* ---- 文件树右键菜单的文件操作(`contextmenu.file`,见 protocol.ts file_*) ---- */
|
|
@@ -1176,6 +1191,113 @@ export class FilesService {
|
|
|
1176
1191
|
}
|
|
1177
1192
|
return join(dir, `${stem} copy ${Date.now()}${ext}`);
|
|
1178
1193
|
}
|
|
1194
|
+
/** 系统原生打开/定位的公共执行体(issue #187):cmd/args 已按平台组装好。
|
|
1195
|
+
* spawn 成功即算送达(explorer/open 都是 daemon 式返回,exit code 不可信);
|
|
1196
|
+
* ENOENT(headless/无桌面)等失败一律 warning notice,绝不抛。 */
|
|
1197
|
+
async spawnDetached(cmd, args, okText, okTextEn) {
|
|
1198
|
+
const fail = (detail) => this.host.emit({
|
|
1199
|
+
type: "notice",
|
|
1200
|
+
level: "warning",
|
|
1201
|
+
text: "无法打开系统文件管理:" + detail + "(远端/无桌面主机不支持)",
|
|
1202
|
+
textEn: "Cannot open system file manager: " + detail + " (unsupported on remote/headless hosts)",
|
|
1203
|
+
});
|
|
1204
|
+
try {
|
|
1205
|
+
const { spawn } = await import("node:child_process");
|
|
1206
|
+
// ⚠ 这里绝不能加 windowsHide: true:它经 STARTF_USESHOWWINDOW + SW_HIDE 压住子进程首窗口,
|
|
1207
|
+
// explorer/open 起的是 GUI(无控制台可藏),加了之后进程在、窗口永远不出来
|
|
1208
|
+
// (2026-09 实测:notepad/explorer 同参数起,进程 session 1 正常、桌面无窗口;去掉即现)。
|
|
1209
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
|
|
1210
|
+
if (typeof child.unref === "function")
|
|
1211
|
+
child.unref();
|
|
1212
|
+
const launched = await new Promise((resolve) => {
|
|
1213
|
+
let done = false;
|
|
1214
|
+
const settle = (v) => {
|
|
1215
|
+
if (!done) {
|
|
1216
|
+
done = true;
|
|
1217
|
+
resolve(v);
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
child.on("spawn", () => settle(true));
|
|
1221
|
+
child.on("error", () => settle(false));
|
|
1222
|
+
// 极端平台无 spawn 事件时兜底放行(进程已脱离,成败不再可知)。
|
|
1223
|
+
setTimeout(() => settle(true), 3000);
|
|
1224
|
+
});
|
|
1225
|
+
if (!launched) {
|
|
1226
|
+
fail(cmd);
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
this.host.emit({ type: "notice", level: "info", text: okText, textEn: okTextEn });
|
|
1230
|
+
}
|
|
1231
|
+
catch (e) {
|
|
1232
|
+
fail(e.message);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
/** 在系统资源管理器中定位(issue #187):文件→打开目录并选中该文件,目录→直接打开。
|
|
1236
|
+
* 只读操作(不改文件),保护根/盘符根也允许;@root 本体与越界路径拒绝。 */
|
|
1237
|
+
async revealEntry(path) {
|
|
1238
|
+
const err = (text, textEn) => this.host.emit({ type: "notice", level: "warning", text, textEn });
|
|
1239
|
+
try {
|
|
1240
|
+
const fsp = await import("node:fs/promises");
|
|
1241
|
+
const { dirname } = await import("node:path");
|
|
1242
|
+
const t = this.resolveOpTarget(path);
|
|
1243
|
+
if (!t) {
|
|
1244
|
+
err("此处不可定位:" + path, "Cannot reveal here: " + path);
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
const st = await fsp.stat(t.abs).catch(() => null);
|
|
1248
|
+
if (!st) {
|
|
1249
|
+
err("文件不存在:" + path, "Not found: " + path);
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
const isDir = st.isDirectory();
|
|
1253
|
+
const segs = path.split("/");
|
|
1254
|
+
const base = segs[segs.length - 1] ?? path;
|
|
1255
|
+
if (process.platform === "win32") {
|
|
1256
|
+
// /select, 与路径分两个 argv 传(explorer 对此格式稳定支持,路径含空格也无碍)。
|
|
1257
|
+
// 目录传 /n, 强制打开新窗口,防止若该目录已在后台打开时被 Windows 静默复用且因反抢焦点机制不置顶。
|
|
1258
|
+
await this.spawnDetached("explorer.exe", isDir ? ["/n,", t.abs] : ["/select,", t.abs], "已在资源管理器中显示:" + base, "Revealed in File Explorer: " + base);
|
|
1259
|
+
}
|
|
1260
|
+
else if (process.platform === "darwin") {
|
|
1261
|
+
await this.spawnDetached("open", isDir ? [t.abs] : ["-R", t.abs], "已在访达中显示:" + base, "Revealed in Finder: " + base);
|
|
1262
|
+
}
|
|
1263
|
+
else {
|
|
1264
|
+
// Linux 无统一选中语义:打开其父目录(目录则打开自身)。
|
|
1265
|
+
await this.spawnDetached("xdg-open", [isDir ? t.abs : dirname(t.abs)], "已打开所在目录:" + base, "Opened containing folder: " + base);
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
catch (e) {
|
|
1269
|
+
err("定位失败:" + e.message, "Reveal failed: " + e.message);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
/** 用系统默认应用打开文件(issue #187):仅文件;目录请用 reveal。 */
|
|
1273
|
+
async openDefaultEntry(path) {
|
|
1274
|
+
const err = (text, textEn) => this.host.emit({ type: "notice", level: "warning", text, textEn });
|
|
1275
|
+
try {
|
|
1276
|
+
const fsp = await import("node:fs/promises");
|
|
1277
|
+
const t = this.resolveOpTarget(path);
|
|
1278
|
+
if (!t) {
|
|
1279
|
+
err("此处不可打开:" + path, "Cannot open here: " + path);
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
const st = await fsp.stat(t.abs).catch(() => null);
|
|
1283
|
+
if (!st) {
|
|
1284
|
+
err("文件不存在:" + path, "Not found: " + path);
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
if (!st.isFile()) {
|
|
1288
|
+
err("请选择文件(目录请用“在资源管理器中显示”)", 'Please select a file (use "Reveal" for folders)');
|
|
1289
|
+
return;
|
|
1290
|
+
}
|
|
1291
|
+
const segs = path.split("/");
|
|
1292
|
+
const base = segs[segs.length - 1] ?? path;
|
|
1293
|
+
// explorer 直接跟路径即走默认关联打开(含空格路径单 argv,无拆分问题)。
|
|
1294
|
+
const cmd = process.platform === "win32" ? "explorer.exe" : process.platform === "darwin" ? "open" : "xdg-open";
|
|
1295
|
+
await this.spawnDetached(cmd, [t.abs], "已用默认应用打开:" + base, "Opened with default app: " + base);
|
|
1296
|
+
}
|
|
1297
|
+
catch (e) {
|
|
1298
|
+
err("打开失败:" + e.message, "Open failed: " + e.message);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1179
1301
|
/**
|
|
1180
1302
|
* Path completion for the cwd input: expand ~/relative paths, list the parent
|
|
1181
1303
|
* directory, and return prefix matches (dirs first, capped).
|