pi-web-ui 0.89.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.
@@ -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_*) ---- */
@@ -1188,7 +1203,10 @@ export class FilesService {
1188
1203
  });
1189
1204
  try {
1190
1205
  const { spawn } = await import("node:child_process");
1191
- const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
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" });
1192
1210
  if (typeof child.unref === "function")
1193
1211
  child.unref();
1194
1212
  const launched = await new Promise((resolve) => {
@@ -1236,7 +1254,8 @@ export class FilesService {
1236
1254
  const base = segs[segs.length - 1] ?? path;
1237
1255
  if (process.platform === "win32") {
1238
1256
  // /select, 与路径分两个 argv 传(explorer 对此格式稳定支持,路径含空格也无碍)。
1239
- await this.spawnDetached("explorer.exe", isDir ? [t.abs] : ["/select,", t.abs], "已在资源管理器中显示:" + base, "Revealed in File Explorer: " + base);
1257
+ // 目录传 /n, 强制打开新窗口,防止若该目录已在后台打开时被 Windows 静默复用且因反抢焦点机制不置顶。
1258
+ await this.spawnDetached("explorer.exe", isDir ? ["/n,", t.abs] : ["/select,", t.abs], "已在资源管理器中显示:" + base, "Revealed in File Explorer: " + base);
1240
1259
  }
1241
1260
  else if (process.platform === "darwin") {
1242
1261
  await this.spawnDetached("open", isDir ? [t.abs] : ["-R", t.abs], "已在访达中显示:" + base, "Revealed in Finder: " + base);