pi-web-ui 0.111.0 → 0.113.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 +92 -2
- package/bin/frp-manager.mjs +9 -2
- package/bin/pi-web-ui.mjs +325 -45
- package/dist/server/agent-service-daemon.js +29 -4
- package/dist/server/agent-service.js +1527 -510
- package/dist/server/approval-audit.js +119 -0
- package/dist/server/approval-default-rules.js +4 -4
- package/dist/server/approval-rules.js +42 -17
- package/dist/server/attachment-store.js +8 -8
- package/dist/server/canvas/canvas-agent-tool.js +8 -0
- package/dist/server/canvas/canvas-orchestrator.js +128 -22
- package/dist/server/canvas/pstack-skills-data.js +498 -0
- package/dist/server/client-state.js +28 -0
- package/dist/server/delegate-mode.js +6 -3
- package/dist/server/delegate-task.js +18 -3
- package/dist/server/dispatch-domain-handlers.js +39 -11
- package/dist/server/dsh/dsh-agent-service.js +294 -15
- package/dist/server/dsh/dsh-serialize.js +1 -1
- package/dist/server/durable/durable-driver.js +112 -107
- package/dist/server/durable/durable-event-projector.js +253 -0
- package/dist/server/durable/durable-loader.js +1 -14
- package/dist/server/durable/durable-models.js +107 -0
- package/dist/server/durable/index.js +0 -4
- package/dist/server/engine-probe.js +111 -48
- package/dist/server/eval-tool.js +28 -3
- package/dist/server/goal-service.js +7 -0
- package/dist/server/index.js +371 -57
- package/dist/server/json-utils.js +57 -0
- package/dist/server/marker-service.js +8 -0
- package/dist/server/message-window.js +43 -10
- package/dist/server/model-admin.js +247 -163
- package/dist/server/model-resolver.js +66 -44
- package/dist/server/plan-manager.js +3 -6
- package/dist/server/plugin-api-catalog.js +1 -0
- package/dist/server/plugin-assets.js +238 -0
- package/dist/server/plugin-facilities.js +22 -0
- package/dist/server/plugin-ui-slots.js +1 -0
- package/dist/server/plugins.js +209 -11
- package/dist/server/preset-fields.js +25 -1
- package/dist/server/preset-share.js +5 -2
- package/dist/server/prompt-assembler.js +2 -1
- package/dist/server/prompt-composer.js +18 -8
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-utils.js +156 -0
- package/dist/server/remote-ssh-service.js +110 -12
- package/dist/server/sdk-builtin-extensions.js +85 -0
- package/dist/server/serialize.js +1 -1
- package/dist/server/server-config.js +66 -0
- package/dist/server/session-parser.js +49 -13
- package/dist/server/session-search.js +4 -3
- package/dist/server/settings-service.js +74 -53
- package/dist/server/setup-page.js +632 -0
- package/dist/server/skill-discovery.js +361 -59
- package/dist/server/skill-maintenance.js +231 -0
- package/dist/server/skill-tool.js +32 -3
- package/dist/server/soft-cap.js +30 -6
- package/dist/server/subagent-helpers.js +22 -1
- package/dist/server/subagent-notify.js +93 -0
- package/dist/server/subagent-security-gate.js +282 -0
- package/dist/server/subagent-templates.js +8 -0
- package/dist/server/subagents.js +390 -48
- package/dist/server/terminals.js +196 -8
- package/dist/server/text-quote.js +61 -0
- package/dist/server/tool-approval.js +63 -4
- package/dist/server/tool-guards.js +208 -0
- package/dist/server/tool-host-factories.js +48 -10
- package/dist/server/tool-manager.js +106 -28
- package/dist/server/tool-overrides.js +21 -11
- package/dist/server/universal/driver-base.js +8 -0
- package/dist/server/universal/drivers/claude-code.js +116 -7
- package/dist/server/universal/drivers/dsh-driver.js +3 -0
- package/dist/server/universal/index.js +0 -1
- package/dist/server/universal/universal-session.js +106 -10
- package/dist/server/worktree-service.js +189 -1
- package/docs/dsh-engine.md +1 -5
- package/package.json +1 -1
- package/plugin-sdk/client-utils.mjs +192 -5
- package/plugin-sdk/index.d.ts +63 -1
- package/plugin-sdk/index.mjs +94 -0
- package/plugin-sdk/package.json +5 -1
- package/plugins/catalog.json +21 -0
- package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
- package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
- package/web/dist/assets/index-BwL7qBh6.css +1 -0
- package/web/dist/index.html +11 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-B0ajS__T.js +0 -697
- package/web/dist/assets/index-BHik5WGG.css +0 -1
package/dist/server/index.js
CHANGED
|
@@ -19,13 +19,13 @@
|
|
|
19
19
|
// MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
|
|
20
20
|
import "./patch-remote-catalog.js";
|
|
21
21
|
import "./patch-turn-end-boundary.js";
|
|
22
|
-
import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
|
|
22
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
23
23
|
import { readFile, stat } from "node:fs/promises";
|
|
24
24
|
import { createServer, request as proxyRequest } from "node:http";
|
|
25
25
|
import { createConnection } from "node:net";
|
|
26
26
|
import { basename, delimiter, join, resolve, sep } from "node:path";
|
|
27
27
|
import { homedir } from "node:os";
|
|
28
|
-
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
28
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
29
29
|
import express from "express";
|
|
30
30
|
import compression from "compression";
|
|
31
31
|
import { WebSocket, WebSocketServer } from "ws";
|
|
@@ -35,7 +35,7 @@ import { PROTOCOL_VERSION } from "./protocol-version.js";
|
|
|
35
35
|
import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
|
|
36
36
|
import { ClientStateStore } from "./client-state.js";
|
|
37
37
|
import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-service.js";
|
|
38
|
-
import { httpHostAllowed } from "./host-guard.js";
|
|
38
|
+
import { httpHostAllowed, isLoopbackHost, hostWithoutPort } from "./host-guard.js";
|
|
39
39
|
import { registerFileTransferRoutes } from "./file-transfer-routes.js";
|
|
40
40
|
import { initAttachmentStore, readAttachment } from "./attachment-store.js";
|
|
41
41
|
import { isAudioFile, previewKind } from "./text-sniff.js";
|
|
@@ -52,7 +52,7 @@ import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
|
|
|
52
52
|
import { validateClientId } from "./ws-client-id.js";
|
|
53
53
|
import { PendingCommandQueue } from "./ws-pending-queue.js";
|
|
54
54
|
import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
|
|
55
|
-
import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
|
|
55
|
+
import { PluginManager, resolvePluginClientFile, resolvePluginSharedFile, } from "./plugins.js";
|
|
56
56
|
import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
|
|
57
57
|
import { syncPluginCatalog } from "./plugin-catalog-sync.js";
|
|
58
58
|
import { McpBridge } from "./mcp-bridge.js";
|
|
@@ -62,6 +62,8 @@ import { SchedulerStore } from "./scheduler-tasks.js";
|
|
|
62
62
|
import { initHttpProxy } from "./http-proxy.js";
|
|
63
63
|
import { globalLspPool } from "./lsp-tool.js";
|
|
64
64
|
import { buildPiWebTokenCookie, decodeCookieToken, isTlsRequest } from "./auth-cookie.js";
|
|
65
|
+
import { isLoopbackAddress, loadServerFileConfig, saveServerFileConfig, tokenWarning } from "./server-config.js";
|
|
66
|
+
import { renderSetupHtml } from "./setup-page.js";
|
|
65
67
|
import { getAppVersion, getPkgRoot } from "./pkg-info.js";
|
|
66
68
|
import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePresetAndDshMessage, handleModelAndProviderMessage, handleTerminalMessage, handleSessionLifecycleMessage, handlePlanAndGoalMessage, handleScheduleMessage, handleSettingsMessage, handleInteractiveResponseMessage, handleRemoteSshMessage, } from "./dispatch-domain-handlers.js";
|
|
67
69
|
import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
|
|
@@ -97,14 +99,6 @@ function cliFlag(name) {
|
|
|
97
99
|
}
|
|
98
100
|
return undefined;
|
|
99
101
|
}
|
|
100
|
-
const PORT = Number(cliFlag("--port") ?? process.env.PI_WEB_PORT ?? 8787);
|
|
101
|
-
// #506:直启路径与 bin 层对齐做端口校验——`--port abc` / `PI_WEB_PORT=abc` 之前会
|
|
102
|
-
// listen(NaN) 被 Node 当 0 绑到随机端口,且日志打印 http://localhost:NaN。
|
|
103
|
-
if (!Number.isInteger(PORT) || PORT <= 0 || PORT > 65535) {
|
|
104
|
-
console.error(`无效端口: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
|
|
105
|
-
console.error(`Invalid port: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
|
|
106
|
-
process.exit(1);
|
|
107
|
-
}
|
|
108
102
|
const CWD = resolve(cliFlag("--cwd") ?? process.env.PI_WEB_CWD ?? process.cwd());
|
|
109
103
|
const DATA_DIR = resolve(cliFlag("--data-dir") ?? process.env.PI_WEB_DATA_DIR ?? join(homedir(), ".pi-web"));
|
|
110
104
|
// The data dir is where the control socket, client state, plugins, themes and
|
|
@@ -125,6 +119,16 @@ try {
|
|
|
125
119
|
catch (err) {
|
|
126
120
|
console.warn(`[cwd] 无法创建工作区目录 ${CWD}: ${err.message}`);
|
|
127
121
|
}
|
|
122
|
+
/** 本地 setup 页持久化:<dataDir>/server-config.json(命令行 > 环境变量 > 本文件 > 默认)。 */
|
|
123
|
+
const FILE_CFG = loadServerFileConfig(DATA_DIR);
|
|
124
|
+
const PORT = Number(cliFlag("--port") ?? process.env.PI_WEB_PORT ?? FILE_CFG.port ?? 8787);
|
|
125
|
+
// #506:直启路径与 bin 层对齐做端口校验——`--port abc` / `PI_WEB_PORT=abc` 之前会
|
|
126
|
+
// listen(NaN) 被 Node 当 0 绑到随机端口,且日志打印 http://localhost:NaN。
|
|
127
|
+
if (!Number.isInteger(PORT) || PORT <= 0 || PORT > 65535) {
|
|
128
|
+
console.error(`无效端口: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
|
|
129
|
+
console.error(`Invalid port: ${cliFlag("--port") ?? process.env.PI_WEB_PORT} (--port / PI_WEB_PORT)`);
|
|
130
|
+
process.exit(1);
|
|
131
|
+
}
|
|
128
132
|
// issue #295:工作区直接就是家目录时,SDK 初始化期的同步目录扫描会落在 $HOME 上
|
|
129
133
|
// (iCloud 占位符/外部卷坏挂载 → scandir/open 内核挂起 → 事件循环假死,hello 后无
|
|
130
134
|
// ready)。新装服务默认已是 ~/pi-web-ui(见 bin/pi-web-ui.mjs serviceOptions);
|
|
@@ -154,24 +158,33 @@ function readDevNoCacheSetting() {
|
|
|
154
158
|
/** Bind address. Default is loopback ONLY — the service is a local personal
|
|
155
159
|
* tool and should not be reachable from the network unless explicitly asked
|
|
156
160
|
* (e.g. PI_WEB_HOST=0.0.0.0 for LAN access / Docker port mapping). */
|
|
157
|
-
const HOST = cliFlag("--host") ?? process.env.PI_WEB_HOST ?? "127.0.0.1";
|
|
161
|
+
const HOST = cliFlag("--host") ?? process.env.PI_WEB_HOST ?? FILE_CFG.host ?? "127.0.0.1";
|
|
158
162
|
/** Optional strict hostname allowlist (comma-separated) — only used when set.
|
|
159
163
|
* Origin / Host same-authority matching happens regardless. */
|
|
160
|
-
const ALLOW_HOSTS = (process.env.PI_WEB_ALLOW_HOSTS ?? "")
|
|
164
|
+
const ALLOW_HOSTS = (process.env.PI_WEB_ALLOW_HOSTS ?? FILE_CFG.allowHosts ?? "")
|
|
161
165
|
.split(",")
|
|
162
166
|
.map((s) => s.trim().toLowerCase())
|
|
163
167
|
.filter(Boolean);
|
|
164
168
|
/** Optional extra Origins allowed through the same-authority check (comma-
|
|
165
169
|
* separated, e.g. reverse-proxy setups where the browser origin differs
|
|
166
170
|
* from the Host the backend sees). */
|
|
167
|
-
const ALLOW_ORIGINS = (process.env.PI_WEB_ALLOW_ORIGINS ?? "")
|
|
171
|
+
const ALLOW_ORIGINS = (process.env.PI_WEB_ALLOW_ORIGINS ?? FILE_CFG.allowOrigins ?? "")
|
|
168
172
|
.split(",")
|
|
169
173
|
.map((s) => s.trim().toLowerCase())
|
|
170
174
|
.filter(Boolean);
|
|
171
175
|
/** 可选共享口令(PI_WEB_TOKEN):设置后所有 HTTP/WS 请求必须携带——
|
|
172
176
|
* Authorization: Bearer / X-PI-Token 头、?token= 查询参数或 pi_web_token cookie
|
|
173
177
|
* 任一匹配即可;供 0.0.0.0 / 反代等暴露场景兜底,未设置则行为不变。 */
|
|
174
|
-
|
|
178
|
+
let AUTH_TOKEN = (process.env.PI_WEB_TOKEN ?? FILE_CFG.token ?? "").trim();
|
|
179
|
+
/** 显式允许非回环地址无 Token 全开放运行(PI_WEB_INSECURE_NO_AUTH=1 / PI_WEB_ALLOW_INSECURE_NO_AUTH=1)。
|
|
180
|
+
* 默认为 false。未显式开启时,监听非回环地址将自动生成随机高强度 Token 实现零信任自愈保护。 */
|
|
181
|
+
const ALLOW_INSECURE_NO_AUTH = /^(1|true|yes)$/i.test(process.env.PI_WEB_INSECURE_NO_AUTH ?? process.env.PI_WEB_ALLOW_INSECURE_NO_AUTH ?? "");
|
|
182
|
+
/** 零信任自愈口令:非回环监听且未配置口令时自动生成,启动日志中输出带 token 的一键登录链接。 */
|
|
183
|
+
let autoGeneratedToken = "";
|
|
184
|
+
if (!isLoopbackHost(HOST) && !AUTH_TOKEN && !ALLOW_INSECURE_NO_AUTH) {
|
|
185
|
+
autoGeneratedToken = randomBytes(24).toString("hex");
|
|
186
|
+
AUTH_TOKEN = autoGeneratedToken;
|
|
187
|
+
}
|
|
175
188
|
/** 语言包下载根(语言包仓库的 raw 文件地址;版本 tag 优先、main 兜底,见 locales.ts)。 */
|
|
176
189
|
const LOCALE_BASE_URL = process.env.PI_WEB_LOCALE_BASE_URL?.trim() || "https://raw.githubusercontent.com/xing-shuyin/pi-web-ui";
|
|
177
190
|
/**
|
|
@@ -220,6 +233,47 @@ if (process.platform === "win32") {
|
|
|
220
233
|
process.env.PATH = `${windowsBashDir()}${delimiter}${process.env.PATH ?? ""}`;
|
|
221
234
|
void ensureWindowsBash();
|
|
222
235
|
}
|
|
236
|
+
else if (process.platform === "darwin") {
|
|
237
|
+
// macOS launchd 用户代理或 GUI 下,PATH 默认仅 /usr/bin:/bin:/usr/sbin:/sbin。
|
|
238
|
+
// 自动补齐 Homebrew 与常见本地工具目录,确保 claude / git / node 等安装后开箱可用。
|
|
239
|
+
const macPaths = [
|
|
240
|
+
"/opt/homebrew/bin",
|
|
241
|
+
"/usr/local/bin",
|
|
242
|
+
join(homedir(), ".local", "bin"),
|
|
243
|
+
join(homedir(), "Library", "pnpm"),
|
|
244
|
+
join(homedir(), ".bun", "bin"),
|
|
245
|
+
join(homedir(), ".local", "share", "fnm", "current", "bin"),
|
|
246
|
+
];
|
|
247
|
+
// fnm / nvm 在 macOS 下版本目录自动扫入 PATH
|
|
248
|
+
const fnmVersions = join(homedir(), ".local", "share", "fnm", "node-versions");
|
|
249
|
+
if (existsSync(fnmVersions)) {
|
|
250
|
+
try {
|
|
251
|
+
for (const v of readdirSync(fnmVersions)) {
|
|
252
|
+
macPaths.push(join(fnmVersions, v, "installation", "bin"));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
/* ignore */
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const nvmVersions = join(homedir(), ".nvm", "versions", "node");
|
|
260
|
+
if (existsSync(nvmVersions)) {
|
|
261
|
+
try {
|
|
262
|
+
for (const v of readdirSync(nvmVersions)) {
|
|
263
|
+
macPaths.push(join(nvmVersions, v, "bin"));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
/* ignore */
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const curParts = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
271
|
+
const curSet = new Set(curParts);
|
|
272
|
+
const toAdd = macPaths.filter((p) => existsSync(p) && !curSet.has(p));
|
|
273
|
+
if (toAdd.length > 0) {
|
|
274
|
+
process.env.PATH = `${toAdd.join(delimiter)}${delimiter}${process.env.PATH ?? ""}`;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
223
277
|
const app = express();
|
|
224
278
|
// Host 白名单(防 DNS rebinding,审查 #352):无 token 部署下 HTTP 路由此前
|
|
225
279
|
// 不校验 Host,恶意网页让自己的域名解析到 127.0.0.1 即可打满全部 API。
|
|
@@ -235,6 +289,158 @@ app.use((req, res, next) => {
|
|
|
235
289
|
next();
|
|
236
290
|
});
|
|
237
291
|
app.use(express.json({ limit: "10mb" }));
|
|
292
|
+
/**
|
|
293
|
+
* 只能本地访问的配置页(/setup + /api/setup/*)。
|
|
294
|
+
*
|
|
295
|
+
* - 挂在 token 鉴权中间件之前:忘记口令时正是要靠它重设。
|
|
296
|
+
* - 回环地址硬门禁:非 127/8、::1 进来直接 403(反代/局域网打不到)。
|
|
297
|
+
* - token 修改热生效;host/port/allowlist 写文件后需重启服务。
|
|
298
|
+
*/
|
|
299
|
+
export function setupGate(req, res, next) {
|
|
300
|
+
// 1. 回环 IP 门禁:TCP 连接必须来自本机
|
|
301
|
+
if (!isLoopbackAddress(req.socket?.remoteAddress)) {
|
|
302
|
+
res.status(403).end("setup page is only available from localhost");
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
// 2. 严禁反代转发:x-forwarded-for / x-real-ip 说明请求来自反代(即使反代在本机回环端口)
|
|
306
|
+
if (req.headers["x-forwarded-for"] || req.headers["x-real-ip"]) {
|
|
307
|
+
res.status(403).end("setup page cannot be accessed through a reverse proxy");
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
// 3. Host 头必须是回环地址(防 DNS rebinding)
|
|
311
|
+
const hostHeader = typeof req.headers.host === "string" ? req.headers.host : "";
|
|
312
|
+
const host = hostWithoutPort(hostHeader);
|
|
313
|
+
if (!host || !isLoopbackHost(host)) {
|
|
314
|
+
res.status(403).end("setup page Host header must be localhost");
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
// 4. Origin 头防跨站(CSRF):若浏览器带了 Origin,必须是回环域
|
|
318
|
+
const origin = typeof req.headers.origin === "string" ? req.headers.origin : "";
|
|
319
|
+
if (origin) {
|
|
320
|
+
try {
|
|
321
|
+
const u = new URL(origin);
|
|
322
|
+
if (!isLoopbackHost(u.hostname)) {
|
|
323
|
+
res.status(403).end("cross-origin setup request rejected");
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
res.status(403).end("invalid origin");
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// 5. 跨站 Fetch 探测防御(Sec-Fetch-Site 防御):
|
|
333
|
+
// 如果是来自外部网站的跨站子资源探测/嵌入(非顶层页面导航),直接拦截。
|
|
334
|
+
// 浏览器地址栏直接输入/回车或者外链跳转到 setup 页时,sec-fetch-site 可能是 cross-site/none,
|
|
335
|
+
// 但其 sec-fetch-dest 是 document / mode 是 navigate;只有跨站的子请求(如 fetch/xhr/image/iframe)才需要阻断。
|
|
336
|
+
const secFetchSite = typeof req.headers["sec-fetch-site"] === "string" ? req.headers["sec-fetch-site"].toLowerCase() : "";
|
|
337
|
+
const secFetchMode = typeof req.headers["sec-fetch-mode"] === "string" ? req.headers["sec-fetch-mode"].toLowerCase() : "";
|
|
338
|
+
if (secFetchSite === "cross-site" && secFetchMode !== "navigate") {
|
|
339
|
+
res.status(403).end("cross-site request to setup rejected");
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
next();
|
|
343
|
+
}
|
|
344
|
+
app.get("/setup", setupGate, (_req, res) => {
|
|
345
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
346
|
+
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
|
|
347
|
+
res.end(renderSetupHtml());
|
|
348
|
+
});
|
|
349
|
+
app.get("/api/setup/status", setupGate, (_req, res) => {
|
|
350
|
+
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
|
|
351
|
+
res.json({
|
|
352
|
+
ok: true,
|
|
353
|
+
token: AUTH_TOKEN,
|
|
354
|
+
tokenSet: AUTH_TOKEN.length > 0,
|
|
355
|
+
tokenWarning: AUTH_TOKEN ? tokenWarning(AUTH_TOKEN) : "",
|
|
356
|
+
host: HOST,
|
|
357
|
+
port: PORT,
|
|
358
|
+
allowHosts: ALLOW_HOSTS.join(","),
|
|
359
|
+
allowOrigins: ALLOW_ORIGINS.join(","),
|
|
360
|
+
configFile: `${DATA_DIR}/server-config.json`,
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
app.post("/api/setup/save", setupGate, (req, res) => {
|
|
364
|
+
const body = (req.body ?? {});
|
|
365
|
+
const prev = loadServerFileConfig(DATA_DIR);
|
|
366
|
+
const next = { ...prev };
|
|
367
|
+
let tokenChanged = false;
|
|
368
|
+
if (typeof body.token === "string") {
|
|
369
|
+
const t = body.token.trim();
|
|
370
|
+
if (t)
|
|
371
|
+
next.token = t;
|
|
372
|
+
else
|
|
373
|
+
delete next.token;
|
|
374
|
+
tokenChanged = t !== AUTH_TOKEN;
|
|
375
|
+
AUTH_TOKEN = t;
|
|
376
|
+
}
|
|
377
|
+
const setStr = (key, v, valid, what) => {
|
|
378
|
+
if (v === undefined)
|
|
379
|
+
return true;
|
|
380
|
+
if (typeof v !== "string") {
|
|
381
|
+
res.status(400).json({ ok: false, error: `${what} 必须是字符串` });
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
const s = v.trim();
|
|
385
|
+
if (s && !valid(s)) {
|
|
386
|
+
res.status(400).json({ ok: false, error: `${what} 格式不合法:${s}` });
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
if (s)
|
|
390
|
+
next[key] = s;
|
|
391
|
+
else
|
|
392
|
+
delete next[key];
|
|
393
|
+
return true;
|
|
394
|
+
};
|
|
395
|
+
if (!setStr("host", body.host, (s) => /^[A-Za-z0-9.:_-]+$/.test(s) && s.length <= 253, "host"))
|
|
396
|
+
return;
|
|
397
|
+
if (!setStr("allowHosts", body.allowHosts, (s) => /^[A-Za-z0-9.,:_\-\s]+$/.test(s), "allowHosts"))
|
|
398
|
+
return;
|
|
399
|
+
if (!setStr("allowOrigins", body.allowOrigins, (s) => s.length <= 2000, "allowOrigins"))
|
|
400
|
+
return;
|
|
401
|
+
if (body.port !== undefined && body.port !== "" && body.port !== null) {
|
|
402
|
+
const p = Number(body.port);
|
|
403
|
+
if (!Number.isInteger(p) || p <= 0 || p > 65535) {
|
|
404
|
+
res.status(400).json({ ok: false, error: `port 必须是 1-65535:${String(body.port)}` });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
next.port = p;
|
|
408
|
+
}
|
|
409
|
+
else if (body.port === "") {
|
|
410
|
+
delete next.port;
|
|
411
|
+
}
|
|
412
|
+
try {
|
|
413
|
+
saveServerFileConfig(DATA_DIR, next);
|
|
414
|
+
}
|
|
415
|
+
catch (err) {
|
|
416
|
+
res.status(500).json({ ok: false, error: `写入配置失败:${err.message}` });
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const norm = (s) => s
|
|
420
|
+
.split(",")
|
|
421
|
+
.map((x) => x.trim().toLowerCase())
|
|
422
|
+
.filter(Boolean)
|
|
423
|
+
.join(",");
|
|
424
|
+
const restartRequired = (typeof body.host === "string" && body.host.trim() !== HOST) ||
|
|
425
|
+
(body.port !== undefined && body.port !== "" && body.port !== null && Number(body.port) !== PORT) ||
|
|
426
|
+
(typeof body.allowHosts === "string" && norm(body.allowHosts) !== ALLOW_HOSTS.join(",")) ||
|
|
427
|
+
(typeof body.allowOrigins === "string" && norm(body.allowOrigins) !== ALLOW_ORIGINS.join(","));
|
|
428
|
+
// 如果设置了新 token,直接给当前回环浏览器下发匹配的 cookie,避免保存后直接 401
|
|
429
|
+
if (AUTH_TOKEN) {
|
|
430
|
+
const secure = isTlsRequest(req);
|
|
431
|
+
res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
|
|
432
|
+
}
|
|
433
|
+
else if (tokenChanged && !AUTH_TOKEN) {
|
|
434
|
+
// 清除了 token,同时清理旧 cookie
|
|
435
|
+
res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
|
|
436
|
+
}
|
|
437
|
+
res.json({
|
|
438
|
+
ok: true,
|
|
439
|
+
tokenApplied: tokenChanged,
|
|
440
|
+
restartRequired,
|
|
441
|
+
saved: next,
|
|
442
|
+
});
|
|
443
|
+
});
|
|
238
444
|
/** 从请求中提取候选 token:头 / 查询参数 / cookie(浏览器导航场景靠 cookie 续命)。 */
|
|
239
445
|
function requestTokens(req) {
|
|
240
446
|
const out = [];
|
|
@@ -305,44 +511,48 @@ function splatParam(req) {
|
|
|
305
511
|
return v.join("/");
|
|
306
512
|
return String(v ?? "");
|
|
307
513
|
}
|
|
308
|
-
|
|
514
|
+
// 常挂载:本地 /setup 页支持运行时设置/清除口令(AUTH_TOKEN 是 let,热旋转)。
|
|
515
|
+
// 无口令时直接放行,保持原有行为不变。
|
|
516
|
+
app.use((req, res, next) => {
|
|
517
|
+
if (!AUTH_TOKEN) {
|
|
518
|
+
next();
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
309
521
|
// /api/health 保持开放:无敏感信息,容器/监控探针需要它。
|
|
310
522
|
// 但绝不能因命中 /api/health 就反射下发真实 token cookie(安全漏洞:issue #45)。
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
});
|
|
345
|
-
}
|
|
523
|
+
const ok = tokenOk(req);
|
|
524
|
+
const cookie = cookieToken(req);
|
|
525
|
+
// 浏览器经 ?token= 首次进入后下发 HttpOnly cookie,后续导航/资源请求免带参数。
|
|
526
|
+
// 重要:只要请求携带着有效 token(query/header/cookie 任一匹配)就把 cookie 刷新为
|
|
527
|
+
// 当前 AUTH_TOKEN——服务端重启改了 PI_WEB_TOKEN 后,旧 cookie 经一次正确的
|
|
528
|
+
// ?token= 进入即被重新同步,无需用户清缓存(issue #71)。
|
|
529
|
+
// Secure 只在 TLS 连接上加:常加会让明文 HTTP(默认 loopback)收不到 cookie。
|
|
530
|
+
const secure = isTlsRequest(req);
|
|
531
|
+
if (ok) {
|
|
532
|
+
// cookieToken 已解码成原文(issue #261),所以直接和原始口令比 ——
|
|
533
|
+
// 以前拿 `encodeURIComponent(AUTH_TOKEN)` 比,含 `=` / 非 ASCII 的口令
|
|
534
|
+
// 永远不相等(于是每个请求都重发 cookie,且带 cookie 的请求反而 401)。
|
|
535
|
+
if (!sameSecret(cookie)) {
|
|
536
|
+
res.setHeader("Set-Cookie", buildPiWebTokenCookie(encodeURIComponent(AUTH_TOKEN), 31536000, secure));
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
else if (cookie) {
|
|
540
|
+
// 请求带的 cookie 已是失效旧值(服务端口令已更换)——立即让其过期,
|
|
541
|
+
// 避免浏览器被残留 cookie 卡死一年(本来也不该再信任它鉴权)。
|
|
542
|
+
// Secure 与非 Secure 在浏览器里是两个独立 cookie:只清一种会因种植时的
|
|
543
|
+
// 协议不同而残留,所以两种属性组合各发一遍(HTTP 下 Secure 那条被忽略,无害)。
|
|
544
|
+
res.setHeader("Set-Cookie", [buildPiWebTokenCookie("", 0, false), buildPiWebTokenCookie("", 0, true)]);
|
|
545
|
+
}
|
|
546
|
+
if (req.path === "/api/health" || ok) {
|
|
547
|
+
next();
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
res
|
|
551
|
+
.status(401)
|
|
552
|
+
.send(cookie
|
|
553
|
+
? "unauthorized: PI_WEB_TOKEN required — 服务端口令已变更?已清除旧 token cookie,请用当前 ?token= 重新进入"
|
|
554
|
+
: "unauthorized: PI_WEB_TOKEN required (?token=…)");
|
|
555
|
+
});
|
|
346
556
|
/** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
|
|
347
557
|
const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
|
|
348
558
|
/** 启动参数显式指定的引擎(--engine pi|dsh|claude|durable 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
|
|
@@ -394,6 +604,7 @@ registerFileTransferRoutes(app, (clientId) => service.get(clientId)?.cwd);
|
|
|
394
604
|
app.get("/api/health", (_req, res) => {
|
|
395
605
|
// 审查 #352:该端点对未鉴权开放(监控探针需要),故只保留版本/引擎与 SDK
|
|
396
606
|
// 副本诊断信息,不再暴露 cwd(工作区路径披露)与 pid(指纹/信息收集面)。
|
|
607
|
+
// issue #763: 支持多实例区分的环境变量 (PI_WEB_INSTANCE_NAME / PI_WEB_FAVICON_COLOR)。
|
|
397
608
|
res.json({
|
|
398
609
|
ok: true,
|
|
399
610
|
piVersion: VERSION,
|
|
@@ -401,6 +612,8 @@ app.get("/api/health", (_req, res) => {
|
|
|
401
612
|
// 用户就不用猜「为什么升了全局 SDK 不生效」。(纯新增字段,piVersion 语义不变。)
|
|
402
613
|
piSdkCopies: sdkCopies(),
|
|
403
614
|
engine: currentDefaultEngine,
|
|
615
|
+
instanceName: process.env.PI_WEB_INSTANCE_NAME?.trim() || undefined,
|
|
616
|
+
faviconColor: process.env.PI_WEB_FAVICON_COLOR?.trim() || undefined,
|
|
404
617
|
});
|
|
405
618
|
});
|
|
406
619
|
/**
|
|
@@ -589,6 +802,11 @@ app.get("/api/office-media", async (req, res) => {
|
|
|
589
802
|
};
|
|
590
803
|
res.setHeader("Content-Type", mimeMap[ext] || "application/octet-stream");
|
|
591
804
|
res.setHeader("Cache-Control", "public, max-age=86400, immutable");
|
|
805
|
+
if (ext === "svg") {
|
|
806
|
+
// 与 /api/attachment 和 /api/file 同理:SVG 文档形态的 <script> 沙箱化(审查 #352 P0-1)
|
|
807
|
+
res.setHeader("Content-Security-Policy", "sandbox");
|
|
808
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
809
|
+
}
|
|
592
810
|
res.send(imgBuf);
|
|
593
811
|
}
|
|
594
812
|
catch {
|
|
@@ -888,6 +1106,27 @@ app.get("/plugins/:id/client/*splat", (req, res) => {
|
|
|
888
1106
|
.end("not found");
|
|
889
1107
|
});
|
|
890
1108
|
});
|
|
1109
|
+
// 插件公共客户端依赖共享库(@pi-web-ui/plugin-sdk/client 等):
|
|
1110
|
+
// 静态托管在 /plugins-shared/*,配合前端 Import Maps 免去各插件重复打包。
|
|
1111
|
+
const PLUGIN_SHARED_DIR = join(pkgRoot, "plugin-sdk");
|
|
1112
|
+
app.get("/plugins-shared/*splat", (req, res) => {
|
|
1113
|
+
const rest = splatParam(req);
|
|
1114
|
+
const abs = resolvePluginSharedFile(PLUGIN_SHARED_DIR, rest);
|
|
1115
|
+
if (!abs || !existsSync(abs)) {
|
|
1116
|
+
res.status(404).end("shared module not found");
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
if (/\.(mjs|js)$/.test(abs)) {
|
|
1120
|
+
res.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
1121
|
+
}
|
|
1122
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
1123
|
+
res.sendFile(abs, { dotfiles: "allow" }, (err) => {
|
|
1124
|
+
if (err && !res.headersSent)
|
|
1125
|
+
res
|
|
1126
|
+
.status(err.statusCode === 404 ? 404 : 500)
|
|
1127
|
+
.end("not found");
|
|
1128
|
+
});
|
|
1129
|
+
});
|
|
891
1130
|
/** Set in the env of the replacement child spawned by a self-update restart. */
|
|
892
1131
|
const RESTART_CHILD_ENV = "PI_WEB_RESTART_CHILD";
|
|
893
1132
|
const webDist = join(pkgRoot, "web", "dist");
|
|
@@ -1539,6 +1778,7 @@ async function confirmPluginInstallHelper(items) {
|
|
|
1539
1778
|
// 远程 SSH 连接管理、环境探针与目录浏览服务
|
|
1540
1779
|
const remoteSshService = new RemoteSshService(DATA_DIR);
|
|
1541
1780
|
setGlobalRemoteSshService(remoteSshService);
|
|
1781
|
+
pluginMgr.provideService("host", "remoteSsh", remoteSshService);
|
|
1542
1782
|
// 多引擎多模型多目录画布协作调度器 (Canvas Studio)
|
|
1543
1783
|
const canvasOrchestrator = new CanvasOrchestrator(CWD, DATA_DIR, (eng) => ensureEngine(eng));
|
|
1544
1784
|
setCanvasRuntime(canvasOrchestrator);
|
|
@@ -1902,13 +2142,17 @@ pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
|
|
|
1902
2142
|
}
|
|
1903
2143
|
};
|
|
1904
2144
|
// llmProvider:插件直调模型(孤立无工具的一次性补全,不建对话)。
|
|
1905
|
-
//
|
|
2145
|
+
// 双引擎适配层:支持 pi 与 dsh 引擎。
|
|
1906
2146
|
pm.llmProvider = async (pluginId, req) => {
|
|
1907
2147
|
try {
|
|
1908
|
-
|
|
2148
|
+
for (const s of activeEngines()) {
|
|
2149
|
+
if (s && typeof s.completeForPlugins === "function") {
|
|
2150
|
+
return await s.completeForPlugins(pluginId, (req ?? {}));
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
1909
2153
|
const svc = ensureEngine("pi");
|
|
1910
2154
|
if (typeof svc.completeForPlugins !== "function")
|
|
1911
|
-
return { ok: false, error: "当前引擎不支持 LLM
|
|
2155
|
+
return { ok: false, error: "当前引擎不支持 LLM 直调" };
|
|
1912
2156
|
return await svc.completeForPlugins(pluginId, (req ?? {}));
|
|
1913
2157
|
}
|
|
1914
2158
|
catch (err) {
|
|
@@ -2323,7 +2567,31 @@ wss.on("connection", (ws) => {
|
|
|
2323
2567
|
// 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
|
|
2324
2568
|
// 放在引擎分发之前:它不是引擎能力,窗口化关闭时静默无回执(前端保持现状)。
|
|
2325
2569
|
if (msg.type === "load_earlier_messages") {
|
|
2326
|
-
windowTap.loadEarlier(
|
|
2570
|
+
let handled = windowTap.loadEarlier({
|
|
2571
|
+
count: msg.count,
|
|
2572
|
+
all: msg.all,
|
|
2573
|
+
conversationId: msg.conversationId,
|
|
2574
|
+
beforeId: msg.beforeId,
|
|
2575
|
+
before: msg.before,
|
|
2576
|
+
});
|
|
2577
|
+
if (!handled && cs) {
|
|
2578
|
+
const activeId = typeof cs.activeConversationId === "function" ? cs.activeConversationId() : undefined;
|
|
2579
|
+
const convId = msg.conversationId || activeId;
|
|
2580
|
+
const full = convId ? cs.getMessagesOfConversation?.(convId) : undefined;
|
|
2581
|
+
if (convId && full && full.length > 0) {
|
|
2582
|
+
windowTap.rehydrate(convId, full, msg.before);
|
|
2583
|
+
handled = windowTap.loadEarlier({
|
|
2584
|
+
count: msg.count,
|
|
2585
|
+
all: msg.all,
|
|
2586
|
+
conversationId: convId,
|
|
2587
|
+
beforeId: msg.beforeId,
|
|
2588
|
+
before: msg.before,
|
|
2589
|
+
});
|
|
2590
|
+
}
|
|
2591
|
+
if (!handled && (!msg.conversationId || msg.conversationId === activeId)) {
|
|
2592
|
+
cs.flushSnapshot(true);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2327
2595
|
return;
|
|
2328
2596
|
}
|
|
2329
2597
|
// Managed instances do not install software on themselves, and tabs this
|
|
@@ -2400,7 +2668,7 @@ wss.on("connection", (ws) => {
|
|
|
2400
2668
|
case "queue_remove":
|
|
2401
2669
|
// #491:removeQueued 是 async——dispatch 是 fire-and-forget,缺 void 时
|
|
2402
2670
|
// 内部抛错即 unhandledRejection,而全仓没有兜底 handler,Node ≥15 直接崩进程。
|
|
2403
|
-
void cs.removeQueued(msg.kind, msg.text, msg.index);
|
|
2671
|
+
void cs.removeQueued(msg.kind, msg.text, msg.index, msg.id);
|
|
2404
2672
|
break;
|
|
2405
2673
|
case "draft_update":
|
|
2406
2674
|
cs.saveDraft?.(msg.sessionId, msg.text, msg.ts);
|
|
@@ -2602,6 +2870,22 @@ wss.on("connection", (ws) => {
|
|
|
2602
2870
|
if (!closed)
|
|
2603
2871
|
send({ type: "engines_status", engines });
|
|
2604
2872
|
});
|
|
2873
|
+
if (autoGeneratedToken) {
|
|
2874
|
+
send({
|
|
2875
|
+
type: "notice",
|
|
2876
|
+
level: "info",
|
|
2877
|
+
text: `零信任保护:服务监听在非回环地址 (${HOST}),已自动生成临时访问 Token 并生效。`,
|
|
2878
|
+
textEn: `Zero-Trust: Server is bound to non-loopback (${HOST}); an ephemeral access token was auto-generated.`,
|
|
2879
|
+
});
|
|
2880
|
+
}
|
|
2881
|
+
else if (!isLoopbackHost(HOST) && !AUTH_TOKEN && ALLOW_INSECURE_NO_AUTH) {
|
|
2882
|
+
send({
|
|
2883
|
+
type: "notice",
|
|
2884
|
+
level: "warning",
|
|
2885
|
+
text: `安全告警:服务监听在非回环地址 (${HOST}) 且开启了免密模式,局域网设备可在未授权状态下访问与执行命令!`,
|
|
2886
|
+
textEn: `Security Warning: Server is bound to non-loopback (${HOST}) in insecure mode; any device on the network can access without authentication!`,
|
|
2887
|
+
});
|
|
2888
|
+
}
|
|
2605
2889
|
}
|
|
2606
2890
|
// attach 慢提示:本体继续等,不取消;完成后照常走快照流程。
|
|
2607
2891
|
const slowTimer = setTimeout(() => {
|
|
@@ -2803,6 +3087,36 @@ httpServer.listen(PORT, HOST, () => {
|
|
|
2803
3087
|
console.log(` pi SDK note : ${sdkNote}`);
|
|
2804
3088
|
}
|
|
2805
3089
|
console.log(` bind : ${HOST}:${PORT}`);
|
|
3090
|
+
console.log(` setup : http://127.0.0.1:${PORT}/setup (仅本机:配 token/监听/白名单)`);
|
|
3091
|
+
if (autoGeneratedToken) {
|
|
3092
|
+
console.log("");
|
|
3093
|
+
console.log(" ╔═══════════════════════════════════════════════════════════════════════════════╗");
|
|
3094
|
+
console.log(" ║ 🛡️ 零信任自愈保护已生效 (Zero-Trust Auto-Remediation) ║");
|
|
3095
|
+
console.log(" ║ 检测到服务监听在非回环地址且未配置口令,系统已自动生成临时访问 Token: ║");
|
|
3096
|
+
console.log(` ║ Token: ${autoGeneratedToken.padEnd(68)} ║`);
|
|
3097
|
+
console.log(" ║ ║");
|
|
3098
|
+
console.log(" ║ 请使用以下带凭据的链接访问 Web 界面(浏览器将自动保存 HttpOnly Cookie): ║");
|
|
3099
|
+
const link = `http://${HOST === "0.0.0.0" ? "127.0.0.1" : HOST}:${PORT}/?token=${autoGeneratedToken}`;
|
|
3100
|
+
console.log(` ║ 👉 ${link.padEnd(73)} ║`);
|
|
3101
|
+
console.log(" ║ ║");
|
|
3102
|
+
console.log(" ║ 若确实需要在局域网完全免密公开,可设置 PI_WEB_INSECURE_NO_AUTH=1 启动。 ║");
|
|
3103
|
+
console.log(" ╚═══════════════════════════════════════════════════════════════════════════════╝");
|
|
3104
|
+
}
|
|
3105
|
+
else if (!isLoopbackHost(HOST) && !AUTH_TOKEN && ALLOW_INSECURE_NO_AUTH) {
|
|
3106
|
+
const requireAuth = /^(1|true|yes)$/i.test(process.env.PI_WEB_REQUIRE_AUTH ?? "");
|
|
3107
|
+
if (requireAuth) {
|
|
3108
|
+
console.error("");
|
|
3109
|
+
console.error(` [FATAL] PI_WEB_REQUIRE_AUTH is enabled, but server is bound to non-loopback host (${HOST}) without PI_WEB_TOKEN.`);
|
|
3110
|
+
console.error(" Please set PI_WEB_TOKEN or bind to 127.0.0.1.");
|
|
3111
|
+
console.error("");
|
|
3112
|
+
process.exit(1);
|
|
3113
|
+
}
|
|
3114
|
+
console.warn("");
|
|
3115
|
+
console.warn(" ─────────────────────────────────────────────────────────────────────────────");
|
|
3116
|
+
console.warn(` ⚠️ 【安全告警】服务监听在非回环地址 (${HOST}:${PORT}) 且显式开启了全开放免密模式 (PI_WEB_INSECURE_NO_AUTH=1)!`);
|
|
3117
|
+
console.warn(" 局域网(或公网路由)任意设备均可在未授权状态下访问 Web 界面并执行系统命令!");
|
|
3118
|
+
console.warn(" ─────────────────────────────────────────────────────────────────────────────");
|
|
3119
|
+
}
|
|
2806
3120
|
console.log("");
|
|
2807
3121
|
});
|
|
2808
3122
|
// 上传文件保留期清理:启动扫一次 + 每 6 小时一次(best-effort,见 uploads.ts)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* json-utils.ts — 跨模块共享 JSON 工具集。
|
|
3
|
+
*
|
|
4
|
+
* 统一收敛带注释 JSON(JSONC)的安全剥离与解析,消除跨模块重复手搓。
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* 剥离 JSON 字符串中的 // 单行注释与 /* *\/ 块级注释。
|
|
8
|
+
* 保护字符串字面量内部内容(如 URL 中的 "https://..." 或包含引号/斜杠的内容)。
|
|
9
|
+
*/
|
|
10
|
+
export function stripJsonComments(src) {
|
|
11
|
+
let out = "";
|
|
12
|
+
let inString = false;
|
|
13
|
+
let i = 0;
|
|
14
|
+
while (i < src.length) {
|
|
15
|
+
const c = src[i];
|
|
16
|
+
const next = src[i + 1];
|
|
17
|
+
if (inString) {
|
|
18
|
+
out += c;
|
|
19
|
+
if (c === "\\") {
|
|
20
|
+
out += next ?? "";
|
|
21
|
+
i += 2;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (c === '"')
|
|
25
|
+
inString = false;
|
|
26
|
+
i++;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (c === '"') {
|
|
30
|
+
inString = true;
|
|
31
|
+
out += c;
|
|
32
|
+
i++;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (c === "/" && next === "/") {
|
|
36
|
+
while (i < src.length && src[i] !== "\n")
|
|
37
|
+
i++;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (c === "/" && next === "*") {
|
|
41
|
+
i += 2;
|
|
42
|
+
while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
|
|
43
|
+
i++;
|
|
44
|
+
i += 2;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
out += c;
|
|
48
|
+
i++;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* 安全解析可能包含注释的 JSON 文本。
|
|
54
|
+
*/
|
|
55
|
+
export function parseJsonWithComments(src) {
|
|
56
|
+
return JSON.parse(stripJsonComments(src));
|
|
57
|
+
}
|