pi-web-ui 0.113.1 → 0.114.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 +71 -1
- package/README.md +187 -316
- package/README.zh-CN.md +227 -299
- package/README.zh-TW.md +227 -299
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/frp-manager.mjs +1573 -1573
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +4081 -4041
- package/deploy/nginx-subpath.conf +100 -100
- package/deploy/pi-web-ui.service +36 -36
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2419 -1174
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +69 -13
- package/dist/server/canvas/canvas-agent-tool.js +68 -18
- package/dist/server/canvas/canvas-cards.js +1 -1
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +519 -202
- package/dist/server/canvas/canvas-scheduled-task.js +45 -0
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +110 -24
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +351 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +830 -0
- package/dist/server/device-center/local-hub.js +92 -0
- package/dist/server/device-center/local.js +529 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +996 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +84 -27
- package/dist/server/dsh/dsh-agent-service.js +282 -159
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
- package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
- package/dist/server/dsh/runtime/launcher.mjs +235 -235
- package/dist/server/dsh/runtime/override.patch.yml +89 -89
- package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/engine-probe.js +36 -6
- package/dist/server/eval-tool.js +135 -135
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +38 -26
- package/dist/server/global-loader.js +40 -2
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +285 -255
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/patch-bash-process.js +125 -0
- package/dist/server/patch-tool.js +9 -9
- package/dist/server/patch-turn-end-boundary.js +3 -3
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/persona-chain.js +8 -8
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +288 -94
- package/dist/server/preset-fields.js +56 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +113 -72
- package/dist/server/prompt-templates.js +106 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +199 -106
- package/dist/server/request-context.js +164 -0
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/schedule-agent-tool.js +39 -21
- package/dist/server/scheduler-tasks.js +106 -55
- package/dist/server/scm-commitmsg.js +10 -10
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +273 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/setup-page.js +620 -620
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/text-quote.js +9 -0
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +48 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/drivers/claude-code.js +5 -0
- package/dist/server/universal/drivers/codex.js +336 -0
- package/dist/server/universal/index.js +1 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-attachments.js +24 -1
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +357 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/vision-bridge.js +18 -18
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/docs/device-center.md +148 -0
- package/docs/device-desktop.md +48 -0
- package/docs/dsh-engine.md +493 -493
- package/extensions/webui.ts +335 -335
- package/package.json +5 -2
- package/plugin-sdk/README.md +174 -174
- package/plugin-sdk/client-utils.mjs +279 -279
- package/plugin-sdk/import-check.mjs +210 -210
- package/plugin-sdk/index.d.ts +698 -676
- package/plugin-sdk/index.mjs +696 -696
- package/plugin-sdk/package.json +13 -13
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +11 -1
- package/themes/aetheris.css +501 -607
- package/themes/ayu-light.css +116 -140
- package/themes/bases/flow-base.css +1357 -1363
- package/themes/bases/obsidian-base.css +895 -895
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +688 -687
- package/themes/bases/zhupi-base.css +660 -659
- package/themes/catppuccin-latte.css +119 -142
- package/themes/catppuccin.css +116 -147
- package/themes/claude-code-dark.css +147 -146
- package/themes/codex.css +114 -138
- package/themes/cyberpunk.css +50 -108
- package/themes/dark-teal.css +264 -265
- package/themes/dazzle.css +38 -108
- package/themes/everforest-light.css +115 -138
- package/themes/flow-light.css +164 -164
- package/themes/flow.css +161 -161
- package/themes/geist.css +114 -138
- package/themes/gruvbox-light.css +115 -138
- package/themes/kanagawa-lotus.css +115 -138
- package/themes/md-preview.css +24 -234
- package/themes/mist.css +166 -186
- package/themes/nord.css +107 -138
- package/themes/one-dark.css +106 -139
- package/themes/paper.css +174 -186
- package/themes/rose-pine-dawn.css +114 -138
- package/themes/sakura.css +166 -186
- package/themes/solarized-light.css +114 -137
- package/themes/tokyo-night.css +115 -146
- package/themes/translucent.css +85 -85
- package/themes/transparent.css +116 -116
- package/themes/vs-code-dark.css +147 -147
- package/themes/wallpaper-flow.css +382 -382
- package/themes/wallpaper-obsidian.css +74 -74
- package/themes/white.css +164 -186
- package/themes/zhujian-dark.css +115 -114
- package/themes/zhujian.css +114 -114
- package/themes/zhupi-dark.css +115 -114
- package/themes/zhupi.css +114 -114
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
- package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
- package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
- package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
- package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
- package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
- package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
- package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
- package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
- package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
- package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
- package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
- package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
- package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
- package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
- package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
- package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
- package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
- package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
- package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
- package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
- package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
- package/web/dist/assets/desktop-YguLbrX1.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
- package/web/dist/assets/index-BPvpea8t.js +85 -0
- package/web/dist/assets/index-D6u8xH0o.js +85 -0
- package/web/dist/assets/index-DDZMv6LO.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +42 -35
- package/web/dist/sw.js +179 -179
- package/web/public/sw.js +179 -179
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
- package/web/dist/assets/index-ByiO9f-N.js +0 -2008
- package/web/dist/assets/index-ycGLh4a4.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, lstat, mkdir, mkdtemp, open, realpath, rename, rm } from "node:fs/promises";
|
|
4
|
+
import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
export const DEVICE_FILE_SYNC_LIMITS = Object.freeze({
|
|
8
|
+
bytes: 8 * 1024 * 1024,
|
|
9
|
+
files: 128,
|
|
10
|
+
staged: 16,
|
|
11
|
+
stagedBytes: 32 * 1024 * 1024,
|
|
12
|
+
});
|
|
13
|
+
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
14
|
+
const run = promisify(execFile);
|
|
15
|
+
const missing = (e) => e.code === "ENOENT";
|
|
16
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
17
|
+
const identity = (s) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}:${s.nlink}`;
|
|
18
|
+
function checkSignal(signal) {
|
|
19
|
+
signal?.throwIfAborted();
|
|
20
|
+
}
|
|
21
|
+
/** Portable paths only. Case-fold duplicates even on case-sensitive hosts so a
|
|
22
|
+
* bundle retains the same meaning when sent to Windows/macOS. */
|
|
23
|
+
function safePath(value) {
|
|
24
|
+
if (typeof value !== "string" ||
|
|
25
|
+
!value ||
|
|
26
|
+
Buffer.byteLength(value, "utf8") > 1024 ||
|
|
27
|
+
Buffer.from(value, "utf8").toString("utf8") !== value ||
|
|
28
|
+
value.normalize("NFC") !== value ||
|
|
29
|
+
isAbsolute(value) ||
|
|
30
|
+
/[\\:\x00-\x1f\x7f]/.test(value))
|
|
31
|
+
throw new Error("Unsafe file path");
|
|
32
|
+
const parts = value.split("/");
|
|
33
|
+
if (parts.length > 32)
|
|
34
|
+
throw new Error("File path is too deep");
|
|
35
|
+
for (const part of parts) {
|
|
36
|
+
if (!part ||
|
|
37
|
+
part === "." ||
|
|
38
|
+
part === ".." ||
|
|
39
|
+
/[. ]$/.test(part) ||
|
|
40
|
+
Buffer.byteLength(part) > 255 ||
|
|
41
|
+
/[<>"|?*]/.test(part) ||
|
|
42
|
+
/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part))
|
|
43
|
+
throw new Error("Unsafe file path component");
|
|
44
|
+
if (/^(\.git|node_modules|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gnupg|\.kube|\.npmrc|\.pypirc|\.netrc|_netrc|\.git-credentials|credentials(?:\..*)?|secrets?(?:\..*)?|tokens?(?:\..*)?|id_(?:rsa|dsa|ecdsa|ed25519)(?:\..*)?|authorized_keys|known_hosts)$/i.test(part) ||
|
|
45
|
+
/\.(?:pem|key|p12|pfx|keystore)$/i.test(part))
|
|
46
|
+
throw new Error("Sensitive file path is denied");
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
function within(root, path) {
|
|
51
|
+
const rel = relative(root, path);
|
|
52
|
+
return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
|
|
53
|
+
}
|
|
54
|
+
/** Reject symlinks/junctions at every existing component, including ancestors. */
|
|
55
|
+
async function checkChain(path, allowMissing = false) {
|
|
56
|
+
const absolute = resolve(path);
|
|
57
|
+
let current = parse(absolute).root;
|
|
58
|
+
const parts = absolute.slice(current.length).split(sep).filter(Boolean);
|
|
59
|
+
for (let i = 0; i < parts.length; i++) {
|
|
60
|
+
current = join(current, parts[i]);
|
|
61
|
+
let s;
|
|
62
|
+
try {
|
|
63
|
+
s = await lstat(current);
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
if (allowMissing && missing(e))
|
|
67
|
+
return;
|
|
68
|
+
throw e;
|
|
69
|
+
}
|
|
70
|
+
if (s.isSymbolicLink())
|
|
71
|
+
throw new Error("Symlink paths are denied");
|
|
72
|
+
if (i < parts.length - 1 && !s.isDirectory())
|
|
73
|
+
throw new Error("Path ancestor is not a directory");
|
|
74
|
+
if (relative(resolve(current), await realpath(current)) !== "")
|
|
75
|
+
throw new Error("Real path changed");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Local capability: root never comes from an incoming bundle. No execution,
|
|
79
|
+
* deletion or implicit directory traversal. Staged transfers are process-local;
|
|
80
|
+
* close/cancel remove only this instance's private transfer directories. Node
|
|
81
|
+
* path checks cannot exclude a hostile OS user racing filesystem operations. */
|
|
82
|
+
export function createDeviceFileSync(config) {
|
|
83
|
+
const root = resolve(config.root);
|
|
84
|
+
const dataDir = resolve(config.dataDir);
|
|
85
|
+
const allowReceive = config.allowReceive === true;
|
|
86
|
+
const storage = join(dataDir, "device-transfers");
|
|
87
|
+
if (within(root, dataDir) || within(root, storage))
|
|
88
|
+
throw new Error("File sync dataDir and transfer storage must be outside the project root");
|
|
89
|
+
const transfers = new Map();
|
|
90
|
+
let total = 0;
|
|
91
|
+
let closed = false;
|
|
92
|
+
let queue = Promise.resolve();
|
|
93
|
+
function serialized(fn) {
|
|
94
|
+
const result = queue.then(fn);
|
|
95
|
+
queue = result.catch(() => { });
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
function active(signal) {
|
|
99
|
+
if (closed)
|
|
100
|
+
throw new Error("File sync is closed");
|
|
101
|
+
checkSignal(signal);
|
|
102
|
+
}
|
|
103
|
+
async function roots() {
|
|
104
|
+
await checkChain(root);
|
|
105
|
+
if (!(await lstat(root)).isDirectory())
|
|
106
|
+
throw new Error("Project root must be a directory");
|
|
107
|
+
await checkChain(storage, true);
|
|
108
|
+
if (within(await realpath(root), dataDir))
|
|
109
|
+
throw new Error("Unsafe data directory");
|
|
110
|
+
}
|
|
111
|
+
async function target(path) {
|
|
112
|
+
safePath(path);
|
|
113
|
+
await roots();
|
|
114
|
+
const full = join(root, ...path.split("/"));
|
|
115
|
+
if (!within(root, full))
|
|
116
|
+
throw new Error("Target escapes project root");
|
|
117
|
+
await checkChain(full, true);
|
|
118
|
+
return full;
|
|
119
|
+
}
|
|
120
|
+
async function readFile(path, signal) {
|
|
121
|
+
active(signal);
|
|
122
|
+
const full = await target(path);
|
|
123
|
+
let before;
|
|
124
|
+
try {
|
|
125
|
+
before = await lstat(full);
|
|
126
|
+
}
|
|
127
|
+
catch (e) {
|
|
128
|
+
if (missing(e))
|
|
129
|
+
return null;
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
if (!before.isFile() || before.nlink > 1)
|
|
133
|
+
throw new Error("Target must be a single-link regular file");
|
|
134
|
+
if (before.size > DEVICE_FILE_SYNC_LIMITS.bytes)
|
|
135
|
+
throw new Error("Target exceeds file budget");
|
|
136
|
+
const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
137
|
+
try {
|
|
138
|
+
const opened = await handle.stat();
|
|
139
|
+
if (!opened.isFile() || identity(opened) !== identity(before))
|
|
140
|
+
throw new Error("File changed while opening");
|
|
141
|
+
// Fixed buffer prevents unbounded allocation if a local writer grows it.
|
|
142
|
+
const buffer = Buffer.alloc(before.size + 1);
|
|
143
|
+
let count = 0;
|
|
144
|
+
while (count < buffer.length) {
|
|
145
|
+
active(signal);
|
|
146
|
+
const result = await handle.read(buffer, count, buffer.length - count, count);
|
|
147
|
+
if (!result.bytesRead)
|
|
148
|
+
break;
|
|
149
|
+
count += result.bytesRead;
|
|
150
|
+
}
|
|
151
|
+
await target(path);
|
|
152
|
+
if (count !== before.size ||
|
|
153
|
+
identity(await handle.stat()) !== identity(before) ||
|
|
154
|
+
identity(await lstat(full)) !== identity(before))
|
|
155
|
+
throw new Error("File changed while reading");
|
|
156
|
+
const bytes = buffer.subarray(0, count);
|
|
157
|
+
return { bytes, snapshot: { hash: hash(bytes), identity: identity(before) } };
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
await handle.close();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function validate(input) {
|
|
164
|
+
const bundle = input;
|
|
165
|
+
if (!bundle ||
|
|
166
|
+
bundle.manifest?.version !== 1 ||
|
|
167
|
+
!Array.isArray(bundle.manifest.files) ||
|
|
168
|
+
!Array.isArray(bundle.files) ||
|
|
169
|
+
!bundle.files.length ||
|
|
170
|
+
bundle.files.length > DEVICE_FILE_SYNC_LIMITS.files ||
|
|
171
|
+
bundle.files.length !== bundle.manifest.files.length)
|
|
172
|
+
throw new Error("Invalid bundle manifest");
|
|
173
|
+
const seen = new Set();
|
|
174
|
+
let size = 0;
|
|
175
|
+
const entries = [];
|
|
176
|
+
const files = [];
|
|
177
|
+
for (let i = 0; i < bundle.files.length; i++) {
|
|
178
|
+
const entry = bundle.manifest.files[i];
|
|
179
|
+
const file = bundle.files[i];
|
|
180
|
+
const path = safePath(entry?.path);
|
|
181
|
+
const key = path.toLowerCase();
|
|
182
|
+
if (seen.has(key))
|
|
183
|
+
throw new Error("Duplicate bundle path");
|
|
184
|
+
seen.add(key);
|
|
185
|
+
if (!Number.isSafeInteger(entry.size) ||
|
|
186
|
+
entry.size < 0 ||
|
|
187
|
+
(size += entry.size) > DEVICE_FILE_SYNC_LIMITS.bytes ||
|
|
188
|
+
typeof entry.sha256 !== "string" ||
|
|
189
|
+
!/^[a-f0-9]{64}$/.test(entry.sha256) ||
|
|
190
|
+
file?.path !== path ||
|
|
191
|
+
typeof file.base64 !== "string" ||
|
|
192
|
+
file.base64.length !== 4 * Math.ceil(entry.size / 3))
|
|
193
|
+
throw new Error("Invalid bundle size or hash");
|
|
194
|
+
const bytes = Buffer.from(file.base64, "base64");
|
|
195
|
+
if (bytes.length !== entry.size || bytes.toString("base64") !== file.base64 || hash(bytes) !== entry.sha256)
|
|
196
|
+
throw new Error("Bundle hash or base64 mismatch");
|
|
197
|
+
entries.push({ path, size: entry.size, sha256: entry.sha256 });
|
|
198
|
+
files.push({ path, base64: file.base64 });
|
|
199
|
+
}
|
|
200
|
+
if (size !== bundle.manifest.totalBytes)
|
|
201
|
+
throw new Error("Bundle total size mismatch");
|
|
202
|
+
for (const key of seen)
|
|
203
|
+
for (const other of seen)
|
|
204
|
+
if (other.startsWith(`${key}/`))
|
|
205
|
+
throw new Error("Bundle file/ancestor collision");
|
|
206
|
+
return { manifest: { version: 1, totalBytes: size, files: entries }, files };
|
|
207
|
+
}
|
|
208
|
+
async function makePreview(id, bundle, signal) {
|
|
209
|
+
const baselines = [];
|
|
210
|
+
const files = [];
|
|
211
|
+
for (const entry of bundle.manifest.files) {
|
|
212
|
+
const current = await readFile(entry.path, signal);
|
|
213
|
+
baselines.push(current?.snapshot ?? null);
|
|
214
|
+
files.push({
|
|
215
|
+
...entry,
|
|
216
|
+
baseline: current?.snapshot.hash ?? null,
|
|
217
|
+
status: !current ? "create" : current.snapshot.hash === entry.sha256 ? "identical" : "conflict",
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const revision = hash(JSON.stringify({ id, files, baselines }));
|
|
221
|
+
return { preview: { id, revision, files }, baselines };
|
|
222
|
+
}
|
|
223
|
+
async function drop(id) {
|
|
224
|
+
const transfer = transfers.get(id);
|
|
225
|
+
if (!transfer)
|
|
226
|
+
return;
|
|
227
|
+
await checkChain(transfer.dir);
|
|
228
|
+
await rm(transfer.dir, { recursive: true, force: false });
|
|
229
|
+
transfers.delete(id);
|
|
230
|
+
total -= transfer.bytes;
|
|
231
|
+
}
|
|
232
|
+
async function persist(bundle, signal) {
|
|
233
|
+
await roots();
|
|
234
|
+
await mkdir(storage, { recursive: true, mode: 0o700 });
|
|
235
|
+
await checkChain(storage);
|
|
236
|
+
const dir = await mkdtemp(join(storage, "transfer-"));
|
|
237
|
+
try {
|
|
238
|
+
const tmp = join(dir, "bundle.tmp");
|
|
239
|
+
const handle = await open(tmp, "wx", 0o600);
|
|
240
|
+
try {
|
|
241
|
+
active(signal);
|
|
242
|
+
await handle.writeFile(JSON.stringify(bundle));
|
|
243
|
+
await handle.sync();
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
await handle.close();
|
|
247
|
+
}
|
|
248
|
+
active(signal);
|
|
249
|
+
await checkChain(dir);
|
|
250
|
+
await rename(tmp, join(dir, "bundle.json"));
|
|
251
|
+
return dir;
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
await rm(dir, { recursive: true, force: true });
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** Same metadata/atomic-replacement policy as file-save.ts, extended to bytes.
|
|
259
|
+
* No direct-write fallback; metadata preservation failure rejects this file. */
|
|
260
|
+
async function overwrite(path, bytes, baseline, signal) {
|
|
261
|
+
if (!["linux", "darwin", "freebsd", "win32"].includes(process.platform))
|
|
262
|
+
throw new Error("Metadata-preserving saves unsupported on this platform");
|
|
263
|
+
const full = await target(path);
|
|
264
|
+
await access(full, constants.W_OK);
|
|
265
|
+
const dir = await mkdtemp(join(dirname(full), ".pi-save-"));
|
|
266
|
+
const staged = join(dir, "content");
|
|
267
|
+
const backup = join(dir, "original");
|
|
268
|
+
let committed = false;
|
|
269
|
+
try {
|
|
270
|
+
if (process.platform !== "win32")
|
|
271
|
+
await run("cp", process.platform === "linux"
|
|
272
|
+
? ["--preserve=mode,ownership,timestamps,xattr", "--", full, staged]
|
|
273
|
+
: ["-p", full, staged], { timeout: 30000, signal });
|
|
274
|
+
const handle = await open(staged, process.platform === "win32" ? "wx" : "r+", 0o600);
|
|
275
|
+
try {
|
|
276
|
+
await handle.writeFile(bytes);
|
|
277
|
+
await handle.truncate(bytes.length);
|
|
278
|
+
await handle.sync();
|
|
279
|
+
}
|
|
280
|
+
finally {
|
|
281
|
+
await handle.close();
|
|
282
|
+
}
|
|
283
|
+
if (process.platform === "linux")
|
|
284
|
+
await run("cp", ["--attributes-only", "--preserve=mode,ownership,timestamps,xattr", "--", full, staged], {
|
|
285
|
+
timeout: 30000,
|
|
286
|
+
signal,
|
|
287
|
+
});
|
|
288
|
+
if (!same((await readFile(path, signal))?.snapshot ?? null, baseline))
|
|
289
|
+
throw new Error("Baseline changed before replacement");
|
|
290
|
+
active(signal);
|
|
291
|
+
await target(path);
|
|
292
|
+
await checkChain(dir);
|
|
293
|
+
if (process.platform === "win32") {
|
|
294
|
+
const script = "$ErrorActionPreference='Stop'; try { [IO.File]::Replace($env:PI_SAVE_SOURCE,$env:PI_SAVE_TARGET,$env:PI_SAVE_BACKUP,$false) } catch { [Console]::Error.WriteLine($_.Exception.ToString()); exit 1 }";
|
|
295
|
+
// Once committing, do not interrupt ReplaceFile: its completion must be known.
|
|
296
|
+
await run("powershell.exe", [
|
|
297
|
+
"-NoLogo",
|
|
298
|
+
"-NoProfile",
|
|
299
|
+
"-NonInteractive",
|
|
300
|
+
"-EncodedCommand",
|
|
301
|
+
Buffer.from(script, "utf16le").toString("base64"),
|
|
302
|
+
], {
|
|
303
|
+
timeout: 30000,
|
|
304
|
+
windowsHide: true,
|
|
305
|
+
env: { ...process.env, PI_SAVE_SOURCE: staged, PI_SAVE_TARGET: full, PI_SAVE_BACKUP: backup },
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
else
|
|
309
|
+
await rename(staged, full);
|
|
310
|
+
committed = true;
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
const hasBackup = await lstat(backup).then(() => true, (e) => {
|
|
314
|
+
if (missing(e))
|
|
315
|
+
return false;
|
|
316
|
+
throw e;
|
|
317
|
+
});
|
|
318
|
+
if (hasBackup)
|
|
319
|
+
throw new Error(`Replacement failed; recovery retained at ${backup}`, { cause: error });
|
|
320
|
+
throw error;
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
const hasBackup = await lstat(backup).then(() => true, (e) => {
|
|
324
|
+
if (missing(e))
|
|
325
|
+
return false;
|
|
326
|
+
throw e;
|
|
327
|
+
});
|
|
328
|
+
if (committed || !hasBackup)
|
|
329
|
+
await rm(dir, { recursive: true, force: true });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return {
|
|
333
|
+
prepare({ paths, signal }) {
|
|
334
|
+
return serialized(async () => {
|
|
335
|
+
active(signal);
|
|
336
|
+
if (!Array.isArray(paths) || !paths.length || paths.length > DEVICE_FILE_SYNC_LIMITS.files)
|
|
337
|
+
throw new Error("Invalid file count");
|
|
338
|
+
const files = [];
|
|
339
|
+
const entries = [];
|
|
340
|
+
let bytes = 0;
|
|
341
|
+
const seen = new Set();
|
|
342
|
+
for (const path of paths) {
|
|
343
|
+
const key = safePath(path).toLowerCase();
|
|
344
|
+
if (seen.has(key))
|
|
345
|
+
throw new Error("Duplicate bundle path");
|
|
346
|
+
seen.add(key);
|
|
347
|
+
const file = await readFile(path, signal);
|
|
348
|
+
if (!file)
|
|
349
|
+
throw new Error("Source file does not exist");
|
|
350
|
+
if ((bytes += file.bytes.length) > DEVICE_FILE_SYNC_LIMITS.bytes)
|
|
351
|
+
throw new Error("Bundle exceeds byte budget");
|
|
352
|
+
entries.push({ path, size: file.bytes.length, sha256: file.snapshot.hash });
|
|
353
|
+
files.push({ path, base64: file.bytes.toString("base64") });
|
|
354
|
+
}
|
|
355
|
+
active(signal);
|
|
356
|
+
return { manifest: { version: 1, totalBytes: bytes, files: entries }, files };
|
|
357
|
+
});
|
|
358
|
+
},
|
|
359
|
+
stage(input, { signal } = {}) {
|
|
360
|
+
return serialized(async () => {
|
|
361
|
+
active(signal);
|
|
362
|
+
if (!allowReceive)
|
|
363
|
+
throw new Error("Receiving files is disabled");
|
|
364
|
+
const bundle = validate(input);
|
|
365
|
+
if (transfers.size >= DEVICE_FILE_SYNC_LIMITS.staged ||
|
|
366
|
+
total + bundle.manifest.totalBytes > DEVICE_FILE_SYNC_LIMITS.stagedBytes)
|
|
367
|
+
throw new Error("Staging budget exceeded");
|
|
368
|
+
const id = randomUUID();
|
|
369
|
+
const result = await makePreview(id, bundle, signal);
|
|
370
|
+
const dir = await persist(bundle, signal);
|
|
371
|
+
try {
|
|
372
|
+
active(signal);
|
|
373
|
+
transfers.set(id, { bundle, ...result, dir, bytes: bundle.manifest.totalBytes });
|
|
374
|
+
total += bundle.manifest.totalBytes;
|
|
375
|
+
return structuredClone(result.preview);
|
|
376
|
+
}
|
|
377
|
+
catch (e) {
|
|
378
|
+
await rm(dir, { recursive: true, force: true });
|
|
379
|
+
throw e;
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
},
|
|
383
|
+
preview(id, { signal } = {}) {
|
|
384
|
+
return serialized(async () => {
|
|
385
|
+
active(signal);
|
|
386
|
+
const transfer = transfers.get(id);
|
|
387
|
+
if (!transfer)
|
|
388
|
+
throw new Error("Unknown transfer");
|
|
389
|
+
const result = await makePreview(id, transfer.bundle, signal);
|
|
390
|
+
active(signal);
|
|
391
|
+
Object.assign(transfer, result);
|
|
392
|
+
return structuredClone(result.preview);
|
|
393
|
+
});
|
|
394
|
+
},
|
|
395
|
+
apply({ id, revision, decisions = {}, signal, }) {
|
|
396
|
+
return serialized(async () => {
|
|
397
|
+
active(signal);
|
|
398
|
+
if (!allowReceive)
|
|
399
|
+
throw new Error("Receiving files is disabled");
|
|
400
|
+
const transfer = transfers.get(id);
|
|
401
|
+
if (!transfer)
|
|
402
|
+
throw new Error("Unknown transfer");
|
|
403
|
+
if (revision !== transfer.preview.revision)
|
|
404
|
+
throw new Error("Preview revision mismatch");
|
|
405
|
+
for (const [path, decision] of Object.entries(decisions))
|
|
406
|
+
if (!transfer.bundle.manifest.files.some((f) => f.path === path) || !["overwrite", "skip"].includes(decision))
|
|
407
|
+
throw new Error("Invalid overwrite decision");
|
|
408
|
+
const report = { id, applied: [], unchanged: [], rejected: [] };
|
|
409
|
+
for (let i = 0; i < transfer.bundle.files.length; i++) {
|
|
410
|
+
const file = transfer.bundle.files[i];
|
|
411
|
+
let created;
|
|
412
|
+
try {
|
|
413
|
+
active(signal);
|
|
414
|
+
if (decisions[file.path] === "skip")
|
|
415
|
+
throw new Error("Skipped by decision");
|
|
416
|
+
const baseline = transfer.baselines[i];
|
|
417
|
+
const current = await readFile(file.path, signal);
|
|
418
|
+
if (!same(current?.snapshot ?? null, baseline))
|
|
419
|
+
throw new Error("Baseline changed; request a new preview");
|
|
420
|
+
if (current?.snapshot.hash === transfer.bundle.manifest.files[i].sha256) {
|
|
421
|
+
report.unchanged.push(file.path);
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
const bytes = Buffer.from(file.base64, "base64");
|
|
425
|
+
if (baseline) {
|
|
426
|
+
if (!Object.hasOwn(decisions, file.path) || decisions[file.path] !== "overwrite")
|
|
427
|
+
throw new Error("Conflict requires explicit overwrite");
|
|
428
|
+
await overwrite(file.path, bytes, baseline, signal);
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
let full = await target(file.path);
|
|
432
|
+
await mkdir(dirname(full), { recursive: true, mode: 0o700 });
|
|
433
|
+
full = await target(file.path);
|
|
434
|
+
active(signal);
|
|
435
|
+
const handle = await open(full, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0), 0o600);
|
|
436
|
+
try {
|
|
437
|
+
created = { full, identity: `${(await handle.stat()).dev}:${(await handle.stat()).ino}` };
|
|
438
|
+
await target(file.path);
|
|
439
|
+
active(signal);
|
|
440
|
+
await handle.writeFile(bytes);
|
|
441
|
+
await handle.sync();
|
|
442
|
+
}
|
|
443
|
+
finally {
|
|
444
|
+
await handle.close();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
report.applied.push(file.path);
|
|
448
|
+
created = undefined;
|
|
449
|
+
}
|
|
450
|
+
catch (error) {
|
|
451
|
+
let reason = error instanceof Error ? error.message : String(error);
|
|
452
|
+
if (created) {
|
|
453
|
+
try {
|
|
454
|
+
await target(file.path);
|
|
455
|
+
const s = await lstat(created.full);
|
|
456
|
+
if (`${s.dev}:${s.ino}` !== created.identity)
|
|
457
|
+
throw new Error("Created file replaced; cleanup refused");
|
|
458
|
+
await rm(created.full);
|
|
459
|
+
}
|
|
460
|
+
catch (e) {
|
|
461
|
+
reason += `; cleanup failed: ${e instanceof Error ? e.message : String(e)}`;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
report.rejected.push({ path: file.path, reason });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
// Keep rejected transfers available for a deliberate new preview/retry.
|
|
468
|
+
if (!report.rejected.length) {
|
|
469
|
+
try {
|
|
470
|
+
await drop(id);
|
|
471
|
+
}
|
|
472
|
+
catch (e) {
|
|
473
|
+
report.cleanupError = e instanceof Error ? e.message : String(e);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return report;
|
|
477
|
+
});
|
|
478
|
+
},
|
|
479
|
+
cancel(id) {
|
|
480
|
+
return serialized(async () => {
|
|
481
|
+
active();
|
|
482
|
+
await drop(id);
|
|
483
|
+
});
|
|
484
|
+
},
|
|
485
|
+
close() {
|
|
486
|
+
closed = true;
|
|
487
|
+
return serialized(async () => {
|
|
488
|
+
for (const id of transfers.keys())
|
|
489
|
+
await drop(id);
|
|
490
|
+
});
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { hashSecret } from "./store.js";
|
|
3
|
+
export const SESSION_COOKIE = "__Host-device_hub";
|
|
4
|
+
export const LOCAL_SESSION_COOKIE = "device_hub";
|
|
5
|
+
export const SESSION_TTL = 7 * 24 * 60 * 60 * 1000;
|
|
6
|
+
function derive(password, salt) {
|
|
7
|
+
return new Promise((resolve, reject) => scrypt(password, salt, 64, { N: 16384, r: 8, p: 1 }, (error, key) => (error ? reject(error) : resolve(key))));
|
|
8
|
+
}
|
|
9
|
+
export async function hashPassword(password) {
|
|
10
|
+
const salt = randomBytes(16).toString("hex");
|
|
11
|
+
return `scrypt:${salt}:${(await derive(password, salt)).toString("hex")}`;
|
|
12
|
+
}
|
|
13
|
+
export async function verifyPassword(password, encoded) {
|
|
14
|
+
const [scheme, salt, hash] = encoded.split(":");
|
|
15
|
+
if (scheme !== "scrypt" || !salt || !hash)
|
|
16
|
+
return false;
|
|
17
|
+
const expected = Buffer.from(hash, "hex");
|
|
18
|
+
const actual = await derive(password, salt);
|
|
19
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
20
|
+
}
|
|
21
|
+
export function createAccountAuth(store, publicUrl) {
|
|
22
|
+
const secure = new URL(publicUrl).protocol === "https:";
|
|
23
|
+
const cookieName = secure ? SESSION_COOKIE : LOCAL_SESSION_COOKIE;
|
|
24
|
+
return {
|
|
25
|
+
cookie(token, clear = false) {
|
|
26
|
+
return `${cookieName}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${clear ? 0 : SESSION_TTL / 1000}${secure ? "; Secure" : ""}`;
|
|
27
|
+
},
|
|
28
|
+
getToken(req) {
|
|
29
|
+
return req.headers.cookie
|
|
30
|
+
?.split(";")
|
|
31
|
+
.map((entry) => entry.trim())
|
|
32
|
+
.find((entry) => entry.startsWith(`${cookieName}=`))
|
|
33
|
+
?.slice(cookieName.length + 1);
|
|
34
|
+
},
|
|
35
|
+
getAccount(req) {
|
|
36
|
+
const token = this.getToken(req);
|
|
37
|
+
if (!token || token.length > 256)
|
|
38
|
+
return null;
|
|
39
|
+
const state = store.snapshot();
|
|
40
|
+
const session = state.sessions.find((entry) => entry.hash === hashSecret(token) && entry.expiresAt > Date.now());
|
|
41
|
+
const account = session && state.accounts.find((entry) => entry.id === session.accountId);
|
|
42
|
+
return account ? { id: account.id, username: account.username } : null;
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Bounded in-memory sliding window; trusts the socket address, never forwarded headers. */
|
|
47
|
+
export class HubRateLimiter {
|
|
48
|
+
limit;
|
|
49
|
+
windowMs;
|
|
50
|
+
entries = new Map();
|
|
51
|
+
constructor(limit, windowMs) {
|
|
52
|
+
this.limit = limit;
|
|
53
|
+
this.windowMs = windowMs;
|
|
54
|
+
}
|
|
55
|
+
allow(key) {
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
for (const [id, entry] of this.entries)
|
|
58
|
+
if (entry.expiresAt <= now)
|
|
59
|
+
this.entries.delete(id);
|
|
60
|
+
let entry = this.entries.get(key);
|
|
61
|
+
if (!entry) {
|
|
62
|
+
if (this.entries.size >= 10000)
|
|
63
|
+
return false;
|
|
64
|
+
entry = { count: 0, expiresAt: now + this.windowMs };
|
|
65
|
+
this.entries.set(key, entry);
|
|
66
|
+
}
|
|
67
|
+
return ++entry.count <= this.limit;
|
|
68
|
+
}
|
|
69
|
+
}
|