pi-web-ui 0.89.0 → 0.90.1
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 +65 -1
- package/README.md +7 -4
- package/README.zh-CN.md +6 -3
- package/bin/pi-web-ui.mjs +37 -10
- package/deploy/pi-web-ui.service +36 -31
- package/dist/server/agent-service.js +651 -112
- package/dist/server/auth-cookie.js +23 -0
- package/dist/server/client-state.js +13 -0
- package/dist/server/composer-drafts.js +20 -2
- package/dist/server/dsh/dsh-agent-service.js +14 -8
- package/dist/server/file-archives.js +258 -0
- package/dist/server/file-transfer-routes.js +113 -0
- package/dist/server/files-service.js +22 -3
- package/dist/server/index.js +169 -31
- package/dist/server/marker-service.js +3 -1
- package/dist/server/plugins.js +12 -4
- package/dist/server/queue-utils.js +16 -0
- package/dist/server/schedule-agent-tool.js +240 -0
- package/dist/server/scheduler-tasks.js +9 -0
- package/dist/server/settings-service.js +68 -1
- package/dist/server/terminals.js +50 -20
- package/dist/server/tool-manager.js +11 -1
- package/dist/server/update-check.js +10 -6
- package/dist/server/webui-context.js +4 -0
- package/dist/server/ws-unknown-types.js +44 -0
- package/package.json +35 -32
- package/web/dist/assets/TerminalPanel-CkxM4Byl.js +3 -0
- package/web/dist/assets/index-DJIV4A-t.js +355 -0
- package/web/dist/assets/index-DLdcRBs_.css +1 -0
- package/web/dist/assets/markdown-CCeVCbci.css +1 -0
- package/web/dist/assets/markdown-eUQn_o9D.js +296 -0
- package/web/dist/assets/react-CR5VJ85Q.js +9 -0
- package/web/dist/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/web/dist/assets/xterm-B1njb2Cr.css +1 -0
- package/web/dist/assets/xterm-Cf5xxe4g.js +16 -0
- package/web/dist/index.html +6 -4
- package/web/dist/assets/TerminalPanel-BOUmN3uu.js +0 -6
- package/web/dist/assets/TerminalPanel-DOrYoP_4.css +0 -32
- package/web/dist/assets/index-3XU67qMh.js +0 -376
- package/web/dist/assets/index-B-gdvWtW.css +0 -10
- package/web/dist/assets/markdown-D3PKeHAZ.js +0 -311
- package/web/dist/assets/react-w24rH0km.js +0 -24
- package/web/dist/assets/xterm-B96xOxS9.js +0 -38
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** True when the browser connection is TLS: direct (`socket.encrypted`,
|
|
2
|
+
* express `req.secure`) or via a TLS-terminating proxy (`x-forwarded-proto`
|
|
3
|
+
* / RFC 7239 `forwarded`). */
|
|
4
|
+
export function isTlsRequest(req) {
|
|
5
|
+
if (req.socket?.encrypted)
|
|
6
|
+
return true;
|
|
7
|
+
if (req.secure === true)
|
|
8
|
+
return true;
|
|
9
|
+
const proto = req.headers?.["x-forwarded-proto"];
|
|
10
|
+
const first = Array.isArray(proto) ? proto[0] : proto;
|
|
11
|
+
if (typeof first === "string" && first.split(",")[0]?.trim().toLowerCase() === "https")
|
|
12
|
+
return true;
|
|
13
|
+
const fwd = req.headers?.forwarded;
|
|
14
|
+
const fwdFirst = Array.isArray(fwd) ? fwd[0] : fwd;
|
|
15
|
+
if (typeof fwdFirst === "string" && /(?:^|[;,]\s*)proto=https(?:[;,]|$)/i.test(fwdFirst))
|
|
16
|
+
return true;
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
/** Build the `Set-Cookie` value for `pi_web_token`. `encodedValue` is already
|
|
20
|
+
* `encodeURIComponent`'d (or `""` when clearing). */
|
|
21
|
+
export function buildPiWebTokenCookie(encodedValue, maxAge, secure) {
|
|
22
|
+
return `pi_web_token=${encodedValue}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
|
|
23
|
+
}
|
|
@@ -71,11 +71,24 @@ export function normalizeUiLayout(v) {
|
|
|
71
71
|
const order = arr(o.order, 200);
|
|
72
72
|
const groups = dict(o.groups, 200);
|
|
73
73
|
const labels = dict(o.labels, 200);
|
|
74
|
+
// 用户对齐:只收 start/center/end(手改脏值回落丢弃,不污染合并结果)。
|
|
75
|
+
let align;
|
|
76
|
+
if (o.align && typeof o.align === "object" && !Array.isArray(o.align)) {
|
|
77
|
+
align = {};
|
|
78
|
+
for (const [k, val] of Object.entries(o.align).slice(0, 200)) {
|
|
79
|
+
if (k.length > 0 && k.length <= 96 && (val === "start" || val === "center" || val === "end")) {
|
|
80
|
+
align[k] = val;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (Object.keys(align).length === 0)
|
|
84
|
+
align = undefined;
|
|
85
|
+
}
|
|
74
86
|
return {
|
|
75
87
|
...(hidden ? { hidden } : {}),
|
|
76
88
|
...(shown ? { shown } : {}),
|
|
77
89
|
...(order ? { order } : {}),
|
|
78
90
|
...(groups ? { groups } : {}),
|
|
91
|
+
...(align ? { align } : {}),
|
|
79
92
|
...(labels ? { labels } : {}),
|
|
80
93
|
};
|
|
81
94
|
}
|
|
@@ -41,6 +41,13 @@ function isValidDraft(d) {
|
|
|
41
41
|
const o = d;
|
|
42
42
|
return typeof o.text === "string" && typeof o.ts === "number" && typeof o.updatedAt === "number";
|
|
43
43
|
}
|
|
44
|
+
/** clear 水位:sessionId → clear 时刻(max(旧条目 ts, Date.now()))。
|
|
45
|
+
* 模块级(非实例级):同进程每个 ClientSession 各有一个 ComposerDraftsStore
|
|
46
|
+
* 实例(agent-service.ts:1922),跨 tab 的 prompt-clear 与陈旧写落在不同
|
|
47
|
+
* 实例上,水位必须跨实例可见。进程重启即失 —— 重启后文件态本身已干净
|
|
48
|
+
* (clear 落盘删 key),late-save 无处可达。
|
|
49
|
+
* ponytail: 内存水位,TTL/持久化按需加(当前重启语义已够用)。 */
|
|
50
|
+
const clearedAt = new Map();
|
|
44
51
|
export class ComposerDraftsStore {
|
|
45
52
|
filePath;
|
|
46
53
|
cache = null;
|
|
@@ -98,10 +105,16 @@ export class ComposerDraftsStore {
|
|
|
98
105
|
return d ? { text: d.text, ts: d.ts } : undefined;
|
|
99
106
|
}
|
|
100
107
|
/** 存一条草稿:空文本 = 删除;同 key 上 ts 更大的才覆盖(last-write-wins,
|
|
101
|
-
* `>=` 让同 ts 的重发幂等)。只有实际变化才写盘。
|
|
108
|
+
* `>=` 让同 ts 的重发幂等)。只有实际变化才写盘。
|
|
109
|
+
* clear 时间戳守卫:prompt() 清掉草稿后才 landing 的旧 `draft_update`
|
|
110
|
+
* (防抖延迟 / 跨 tab 陈旧写,ts <= clearTs)直接丢弃,不复活存储
|
|
111
|
+
* (reload-resurrect,见 clearedAt)。*/
|
|
102
112
|
save(sessionId, text, ts) {
|
|
103
113
|
if (!sessionId)
|
|
104
114
|
return;
|
|
115
|
+
const cut = clearedAt.get(sessionId);
|
|
116
|
+
if (cut !== undefined && ts <= cut)
|
|
117
|
+
return;
|
|
105
118
|
const map = this.load();
|
|
106
119
|
const norm = normalizeDraftText(text);
|
|
107
120
|
if (norm === undefined) {
|
|
@@ -119,11 +132,16 @@ export class ComposerDraftsStore {
|
|
|
119
132
|
map[sessionId] = { text: norm, ts, updatedAt: Date.now() };
|
|
120
133
|
this.persist();
|
|
121
134
|
}
|
|
122
|
-
/** 发送成功 / 会话删除后清掉(有 key
|
|
135
|
+
/** 发送成功 / 会话删除后清掉(有 key 才写盘)。同时记录 clear 时间戳
|
|
136
|
+
* (max(旧条目 ts, Date.now())):之后 ts <= 该水位的 save 一律丢弃,
|
|
137
|
+
* 拦住 prompt() 清掉之后才 landing 的旧 `draft_update`。
|
|
138
|
+
* 模块级共享:同进程多 ClientSession(多 tab)共用同一水位。 */
|
|
123
139
|
clear(sessionId) {
|
|
124
140
|
if (!sessionId)
|
|
125
141
|
return;
|
|
126
142
|
const map = this.load();
|
|
143
|
+
const prevTs = map[sessionId]?.ts ?? 0;
|
|
144
|
+
clearedAt.set(sessionId, Math.max(prevTs, Date.now()));
|
|
127
145
|
if (map[sessionId] !== undefined) {
|
|
128
146
|
delete map[sessionId];
|
|
129
147
|
this.persist();
|
|
@@ -39,6 +39,7 @@ import { TerminalManager, loadCommands, saveCommandsFile } from "../terminals.js
|
|
|
39
39
|
import { saveUpload } from "../uploads.js";
|
|
40
40
|
import { checkAll as checkAllUpdates, collectTargets, resolveNpmRegistry } from "../update-check.js";
|
|
41
41
|
import { previewKind } from "../text-sniff.js";
|
|
42
|
+
import { removeQueuedByIndexOrText } from "../queue-utils.js";
|
|
42
43
|
import { launchOrigin, toServiceInfo } from "../launch-origin.js";
|
|
43
44
|
import { DshRuntime, loadDeepSeekKey } from "./dsh-client.js";
|
|
44
45
|
import { DshStreamAccumulator, assistantMessageEventToUiMessage, toolResultEventToUiMessage, userMessageEventToUiMessage, } from "./dsh-serialize.js";
|
|
@@ -1535,17 +1536,19 @@ export class DshClientSession {
|
|
|
1535
1536
|
await this.promptConv(conv, text, attachments, queue, sysPrefix);
|
|
1536
1537
|
}
|
|
1537
1538
|
/**
|
|
1538
|
-
* Remove ONE queued prompt
|
|
1539
|
+
* Remove ONE queued prompt (the ✕ on a pending bubble). DSH queues are
|
|
1539
1540
|
* display-only — the prompt was already handed to the runtime inbox, so this
|
|
1540
1541
|
* only drops the pending bubble from the UI (there is no per-item runtime
|
|
1541
|
-
* cancel).
|
|
1542
|
+
* cancel). `index` is the clicked bubble's position (duplicate texts need
|
|
1543
|
+
* it); mismatch or omission falls back to first-occurrence text match.
|
|
1542
1544
|
*/
|
|
1543
|
-
removeQueued(kind, text) {
|
|
1545
|
+
removeQueued(kind, text, index) {
|
|
1544
1546
|
const conv = this.conv;
|
|
1545
1547
|
const arr = kind === "steer" ? conv.queue.steering : conv.queue.followUp;
|
|
1546
|
-
const
|
|
1547
|
-
if (
|
|
1548
|
-
arr.splice(
|
|
1548
|
+
const next = removeQueuedByIndexOrText(arr, text, index);
|
|
1549
|
+
if (next.length !== arr.length) {
|
|
1550
|
+
arr.splice(0, arr.length, ...next);
|
|
1551
|
+
}
|
|
1549
1552
|
this.flushSnapshot();
|
|
1550
1553
|
}
|
|
1551
1554
|
/** 向指定会话发提示(审查注入/重发用;不处理 fromDisk fork 与命名)。 */
|
|
@@ -2446,8 +2449,11 @@ export class DshClientSession {
|
|
|
2446
2449
|
async completePath(input) {
|
|
2447
2450
|
await this.files.completePath(input);
|
|
2448
2451
|
}
|
|
2449
|
-
async makeDir(input) {
|
|
2450
|
-
await this.files.makeDir(input);
|
|
2452
|
+
async makeDir(input, setAsCwd = false) {
|
|
2453
|
+
const created = await this.files.makeDir(input);
|
|
2454
|
+
if (created && setAsCwd) {
|
|
2455
|
+
await this.setCwd(created);
|
|
2456
|
+
}
|
|
2451
2457
|
}
|
|
2452
2458
|
// -----------------------------------------------------------------------
|
|
2453
2459
|
// 模型 / 思考
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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);
|