pi-web-ui 0.114.2 → 0.115.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 +55 -1
- package/bin/pi-web-ui.mjs +69 -7
- package/dist/server/agent-service-daemon.js +440 -32
- package/dist/server/agent-service.js +878 -383
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +25 -0
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/context-usage.js +105 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +72 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +328 -10
- package/dist/server/device-center/collab-tool.js +738 -12
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +19 -0
- package/dist/server/device-center/execution-settings.js +100 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +389 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +180 -91
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +208 -0
- package/dist/server/device-center/group-context.js +109 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +178 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub.js +1544 -80
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +18 -0
- package/dist/server/device-center/local.js +356 -40
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +549 -41
- package/dist/server/device-center/store.js +66 -3
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +400 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +815 -8
- package/dist/server/dispatch-domain-handlers.js +21 -3
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +89 -13
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +1 -0
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +5 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +50 -36
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/docs/README.md +94 -0
- package/docs/device-center.md +100 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +1 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
- package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
- package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
- package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
- package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
- package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
- package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
- package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
- package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
- package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
- package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
- package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
- package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
- package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
- package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-CsFs_HMb.css +1 -0
- package/web/dist/assets/index-DHeeHS_l.js +85 -0
- package/web/dist/assets/index-DTZch8uz.js +85 -0
- package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
- package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
- package/web/dist/assets/theme-BXGpyTMh.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
- package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
- package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
- package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
- package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
- package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
- package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
- package/web/dist/assets/index-Cdh3sibd.js +0 -85
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
- package/web/dist/assets/index-DWw_SxRq.js +0 -85
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
|
@@ -0,0 +1,1006 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { lstat, mkdir, open, opendir, readdir, realpath, rename, rm } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { hash, missing, identity, checkSignal, deniedPart, safePath, within, checkChain, computeManifestHash, saveBytesPreservingMetadata, } from "./file-sync-paths.js";
|
|
6
|
+
export { hash, missing, identity, checkSignal, deniedPart, safePath, within, checkChain, computeManifestHash, saveBytesPreservingMetadata, };
|
|
7
|
+
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
8
|
+
export function isUuid(id) {
|
|
9
|
+
return typeof id === "string" && UUID_REGEX.test(id);
|
|
10
|
+
}
|
|
11
|
+
export const CHUNKED_TRANSFER_LIMITS = Object.freeze({
|
|
12
|
+
chunkBytes: 32 * 1024, // 32 KiB default per chunk to stay well within bounded RPC packet budgets
|
|
13
|
+
minChunkBytes: 1024, // 1 KiB min
|
|
14
|
+
maxChunkBytes: 64 * 1024, // 64 KiB max per chunk
|
|
15
|
+
maxTransferBytes: 256 * 1024 * 1024, // 256 MiB total transfer size
|
|
16
|
+
maxFiles: 2048,
|
|
17
|
+
maxVisitedEntries: 16384,
|
|
18
|
+
maxStagedBytes: 512 * 1024 * 1024, // 512 MiB total staged storage
|
|
19
|
+
maxStagedTransfers: 32,
|
|
20
|
+
exclusions: 256,
|
|
21
|
+
exclusionBytes: 16 * 1024,
|
|
22
|
+
});
|
|
23
|
+
export const TRANSFER_LIMITS = CHUNKED_TRANSFER_LIMITS;
|
|
24
|
+
export function validateChunkedManifest(manifest) {
|
|
25
|
+
if (!manifest || typeof manifest !== "object")
|
|
26
|
+
throw new Error("Invalid transfer manifest");
|
|
27
|
+
const m = manifest;
|
|
28
|
+
if (m.version !== 2)
|
|
29
|
+
throw new Error("Unsupported manifest version: expected version 2");
|
|
30
|
+
if (!isUuid(m.transferId))
|
|
31
|
+
throw new Error("Invalid transferId: must be a strict UUID");
|
|
32
|
+
if (!Number.isSafeInteger(m.chunkSize) ||
|
|
33
|
+
m.chunkSize < CHUNKED_TRANSFER_LIMITS.minChunkBytes ||
|
|
34
|
+
m.chunkSize > CHUNKED_TRANSFER_LIMITS.maxChunkBytes)
|
|
35
|
+
throw new Error("Invalid manifest chunkSize");
|
|
36
|
+
if (!Array.isArray(m.files) || !m.files.length || m.files.length > CHUNKED_TRANSFER_LIMITS.maxFiles)
|
|
37
|
+
throw new Error("Invalid manifest file count");
|
|
38
|
+
let computedTotalBytes = 0;
|
|
39
|
+
let computedTotalChunks = 0;
|
|
40
|
+
const seenPaths = new Set();
|
|
41
|
+
for (let i = 0; i < m.files.length; i++) {
|
|
42
|
+
const f = m.files[i];
|
|
43
|
+
if (!f || typeof f !== "object")
|
|
44
|
+
throw new Error("Invalid manifest file entry");
|
|
45
|
+
const p = safePath(f.path);
|
|
46
|
+
const key = p.toLowerCase();
|
|
47
|
+
if (seenPaths.has(key))
|
|
48
|
+
throw new Error("Duplicate manifest file path");
|
|
49
|
+
seenPaths.add(key);
|
|
50
|
+
if (!Number.isSafeInteger(f.size) || f.size < 0 || f.size > CHUNKED_TRANSFER_LIMITS.maxTransferBytes)
|
|
51
|
+
throw new Error(`Invalid file size for ${p}`);
|
|
52
|
+
if (typeof f.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(f.sha256))
|
|
53
|
+
throw new Error(`Invalid sha256 checksum for ${p}`);
|
|
54
|
+
const expectedChunkCount = Math.max(1, Math.ceil(f.size / m.chunkSize));
|
|
55
|
+
if (f.chunkCount !== expectedChunkCount)
|
|
56
|
+
throw new Error(`Invalid chunkCount for ${p}: expected ${expectedChunkCount}, got ${f.chunkCount}`);
|
|
57
|
+
if (f.firstChunkIndex !== computedTotalChunks)
|
|
58
|
+
throw new Error(`Invalid firstChunkIndex for ${p}: expected ${computedTotalChunks}, got ${f.firstChunkIndex}`);
|
|
59
|
+
if (f.offset !== computedTotalBytes)
|
|
60
|
+
throw new Error(`Invalid offset for ${p}: expected ${computedTotalBytes}, got ${f.offset}`);
|
|
61
|
+
if (f.chunkHashes !== undefined) {
|
|
62
|
+
if (!Array.isArray(f.chunkHashes) ||
|
|
63
|
+
f.chunkHashes.length !== expectedChunkCount ||
|
|
64
|
+
!f.chunkHashes.every((h) => typeof h === "string" && /^[a-f0-9]{64}$/.test(h)))
|
|
65
|
+
throw new Error(`Invalid chunkHashes for ${p}`);
|
|
66
|
+
}
|
|
67
|
+
computedTotalBytes += f.size;
|
|
68
|
+
computedTotalChunks += f.chunkCount;
|
|
69
|
+
}
|
|
70
|
+
for (const key of seenPaths) {
|
|
71
|
+
for (const other of seenPaths) {
|
|
72
|
+
if (other.startsWith(`${key}/`))
|
|
73
|
+
throw new Error("Bundle file/ancestor collision");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (m.totalBytes !== computedTotalBytes || m.totalBytes > CHUNKED_TRANSFER_LIMITS.maxTransferBytes)
|
|
77
|
+
throw new Error(`Invalid totalBytes: manifest says ${m.totalBytes}, computed ${computedTotalBytes}`);
|
|
78
|
+
if (m.totalChunks !== computedTotalChunks)
|
|
79
|
+
throw new Error(`Invalid totalChunks: manifest says ${m.totalChunks}, computed ${computedTotalChunks}`);
|
|
80
|
+
const computedHash = computeManifestHash(m.files);
|
|
81
|
+
if (computedHash !== m.manifestHash)
|
|
82
|
+
throw new Error("Manifest hash verification failed");
|
|
83
|
+
return m;
|
|
84
|
+
}
|
|
85
|
+
/** Prepares a chunked transfer manifest from source workspace. */
|
|
86
|
+
export async function prepareChunkedTransfer({ root, paths, recursive = false, chunkSize = CHUNKED_TRANSFER_LIMITS.chunkBytes, transferId = randomUUID(), signal, }) {
|
|
87
|
+
checkSignal(signal);
|
|
88
|
+
if (!isUuid(transferId))
|
|
89
|
+
throw new Error("Invalid transferId: must be a valid UUID");
|
|
90
|
+
const resolvedRoot = resolve(root);
|
|
91
|
+
await checkChain(resolvedRoot, false, signal);
|
|
92
|
+
const rootStat = await lstat(resolvedRoot);
|
|
93
|
+
if (!rootStat.isDirectory())
|
|
94
|
+
throw new Error("Project root must be a directory");
|
|
95
|
+
if (!Array.isArray(paths) || !paths.length || paths.length > CHUNKED_TRANSFER_LIMITS.maxFiles)
|
|
96
|
+
throw new Error("Invalid file count");
|
|
97
|
+
if (typeof recursive !== "boolean")
|
|
98
|
+
throw new Error("Invalid recursive option");
|
|
99
|
+
if (!Number.isSafeInteger(chunkSize) ||
|
|
100
|
+
chunkSize < CHUNKED_TRANSFER_LIMITS.minChunkBytes ||
|
|
101
|
+
chunkSize > CHUNKED_TRANSFER_LIMITS.maxChunkBytes)
|
|
102
|
+
throw new Error("Invalid chunk size");
|
|
103
|
+
const selected = paths.map((path) => safePath(path)).sort();
|
|
104
|
+
for (let i = 0; i < selected.length; i++) {
|
|
105
|
+
const key = selected[i].toLowerCase();
|
|
106
|
+
if (selected.some((other, j) => j !== i && (other.toLowerCase() === key || key.startsWith(`${other.toLowerCase()}/`))))
|
|
107
|
+
throw new Error("Duplicate or overlapping selected path");
|
|
108
|
+
}
|
|
109
|
+
const fileEntries = [];
|
|
110
|
+
const exclusions = [];
|
|
111
|
+
let totalExcluded = 0;
|
|
112
|
+
let summaryFull = false;
|
|
113
|
+
let totalBytes = 0;
|
|
114
|
+
let visited = 0;
|
|
115
|
+
let discoveredFiles = 0;
|
|
116
|
+
const seen = new Set();
|
|
117
|
+
const countVisit = () => {
|
|
118
|
+
checkSignal(signal);
|
|
119
|
+
if (++visited > CHUNKED_TRANSFER_LIMITS.maxVisitedEntries)
|
|
120
|
+
throw new Error("Directory scan entry budget exceeded");
|
|
121
|
+
};
|
|
122
|
+
async function targetPath(p) {
|
|
123
|
+
safePath(p);
|
|
124
|
+
checkSignal(signal);
|
|
125
|
+
const full = join(resolvedRoot, ...p.split("/"));
|
|
126
|
+
if (!within(resolvedRoot, full))
|
|
127
|
+
throw new Error("Target escapes project root");
|
|
128
|
+
await checkChain(full, true, signal);
|
|
129
|
+
return full;
|
|
130
|
+
}
|
|
131
|
+
async function readFileInfo(p) {
|
|
132
|
+
checkSignal(signal);
|
|
133
|
+
const full = await targetPath(p);
|
|
134
|
+
const before = await lstat(full);
|
|
135
|
+
if (!before.isFile() || before.nlink > 1)
|
|
136
|
+
throw new Error("Target must be a single-link regular file");
|
|
137
|
+
if (before.size + totalBytes > CHUNKED_TRANSFER_LIMITS.maxTransferBytes)
|
|
138
|
+
throw new Error("Transfer exceeds byte budget");
|
|
139
|
+
const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
140
|
+
const hasher = createHash("sha256");
|
|
141
|
+
const chunkHashes = [];
|
|
142
|
+
try {
|
|
143
|
+
checkSignal(signal);
|
|
144
|
+
const opened = await handle.stat();
|
|
145
|
+
if (!opened.isFile() || identity(opened) !== identity(before))
|
|
146
|
+
throw new Error("File changed while opening");
|
|
147
|
+
const buf = Buffer.alloc(chunkSize);
|
|
148
|
+
let totalRead = 0;
|
|
149
|
+
while (totalRead < before.size) {
|
|
150
|
+
checkSignal(signal);
|
|
151
|
+
const toRead = Math.min(chunkSize, before.size - totalRead);
|
|
152
|
+
let currentRead = 0;
|
|
153
|
+
while (currentRead < toRead) {
|
|
154
|
+
const res = await handle.read(buf, currentRead, toRead - currentRead, totalRead + currentRead);
|
|
155
|
+
if (!res.bytesRead)
|
|
156
|
+
break;
|
|
157
|
+
currentRead += res.bytesRead;
|
|
158
|
+
}
|
|
159
|
+
if (currentRead !== toRead)
|
|
160
|
+
throw new Error("File changed while reading chunks");
|
|
161
|
+
const chunkSlice = buf.subarray(0, toRead);
|
|
162
|
+
hasher.update(chunkSlice);
|
|
163
|
+
chunkHashes.push(hash(chunkSlice));
|
|
164
|
+
totalRead += toRead;
|
|
165
|
+
}
|
|
166
|
+
const after = await handle.stat();
|
|
167
|
+
if (totalRead !== before.size || identity(after) !== identity(before))
|
|
168
|
+
throw new Error("File changed while reading");
|
|
169
|
+
if (!chunkHashes.length && before.size === 0) {
|
|
170
|
+
chunkHashes.push(hash(Buffer.alloc(0)));
|
|
171
|
+
}
|
|
172
|
+
return { size: before.size, sha256: hasher.digest("hex"), chunkHashes };
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
await handle.close();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function visit(p, selectedPath = false) {
|
|
179
|
+
checkSignal(signal);
|
|
180
|
+
const key = p.toLowerCase();
|
|
181
|
+
if (seen.has(key))
|
|
182
|
+
throw new Error("Duplicate bundle path");
|
|
183
|
+
seen.add(key);
|
|
184
|
+
safePath(p, true);
|
|
185
|
+
const reason = deniedPart(p.split("/").at(-1));
|
|
186
|
+
if (!selectedPath && reason) {
|
|
187
|
+
const excluded = join(resolvedRoot, ...p.split("/"));
|
|
188
|
+
await checkChain(excluded, false, signal);
|
|
189
|
+
totalExcluded++;
|
|
190
|
+
const item = { path: p, reason };
|
|
191
|
+
if (!summaryFull &&
|
|
192
|
+
exclusions.length < CHUNKED_TRANSFER_LIMITS.exclusions &&
|
|
193
|
+
Buffer.byteLength(JSON.stringify([...exclusions, item])) <= CHUNKED_TRANSFER_LIMITS.exclusionBytes)
|
|
194
|
+
exclusions.push(item);
|
|
195
|
+
else
|
|
196
|
+
summaryFull = true;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const full = await targetPath(p);
|
|
200
|
+
const before = await lstat(full);
|
|
201
|
+
if (before.isDirectory()) {
|
|
202
|
+
if (!recursive)
|
|
203
|
+
throw new Error("Directory selection requires recursive: true");
|
|
204
|
+
const directory = await opendir(full);
|
|
205
|
+
const names = [];
|
|
206
|
+
try {
|
|
207
|
+
while (true) {
|
|
208
|
+
checkSignal(signal);
|
|
209
|
+
const entry = await directory.read();
|
|
210
|
+
if (!entry)
|
|
211
|
+
break;
|
|
212
|
+
countVisit();
|
|
213
|
+
if (entry.isSymbolicLink())
|
|
214
|
+
throw new Error("Symlink paths are denied");
|
|
215
|
+
names.push(entry.name);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
await directory.close();
|
|
220
|
+
}
|
|
221
|
+
checkSignal(signal);
|
|
222
|
+
const opened = await lstat(full);
|
|
223
|
+
if (identity(opened) !== identity(before))
|
|
224
|
+
throw new Error("Directory changed while scanning");
|
|
225
|
+
for (const name of names.sort()) {
|
|
226
|
+
await visit(`${p}/${name}`);
|
|
227
|
+
}
|
|
228
|
+
const after = await lstat(full);
|
|
229
|
+
if (identity(after) !== identity(before))
|
|
230
|
+
throw new Error("Directory changed while scanning");
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (++discoveredFiles > CHUNKED_TRANSFER_LIMITS.maxFiles)
|
|
234
|
+
throw new Error("Transfer exceeds file count budget");
|
|
235
|
+
const info = await readFileInfo(p);
|
|
236
|
+
totalBytes += info.size;
|
|
237
|
+
fileEntries.push({ path: p, size: info.size, sha256: info.sha256, chunkHashes: info.chunkHashes });
|
|
238
|
+
}
|
|
239
|
+
for (const p of selected) {
|
|
240
|
+
countVisit();
|
|
241
|
+
await visit(p, true);
|
|
242
|
+
}
|
|
243
|
+
if (!fileEntries.length)
|
|
244
|
+
throw new Error("Selection contains no transferable regular files");
|
|
245
|
+
let globalChunkIndex = 0;
|
|
246
|
+
let currentOffset = 0;
|
|
247
|
+
const files = fileEntries.map((f) => {
|
|
248
|
+
const chunkCount = Math.max(1, Math.ceil(f.size / chunkSize));
|
|
249
|
+
const entry = {
|
|
250
|
+
path: f.path,
|
|
251
|
+
size: f.size,
|
|
252
|
+
sha256: f.sha256,
|
|
253
|
+
offset: currentOffset,
|
|
254
|
+
chunkCount,
|
|
255
|
+
firstChunkIndex: globalChunkIndex,
|
|
256
|
+
chunkHashes: f.chunkHashes,
|
|
257
|
+
};
|
|
258
|
+
globalChunkIndex += chunkCount;
|
|
259
|
+
currentOffset += f.size;
|
|
260
|
+
return entry;
|
|
261
|
+
});
|
|
262
|
+
const manifestHash = computeManifestHash(fileEntries);
|
|
263
|
+
return {
|
|
264
|
+
version: 2,
|
|
265
|
+
transferId,
|
|
266
|
+
totalBytes,
|
|
267
|
+
totalFiles: files.length,
|
|
268
|
+
totalChunks: globalChunkIndex,
|
|
269
|
+
chunkSize,
|
|
270
|
+
files,
|
|
271
|
+
...(totalExcluded ? { exclusions, totalExcluded } : {}),
|
|
272
|
+
manifestHash,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/** Reads a single chunk of data from source file, verifying against expected size or chunk checksum if provided. */
|
|
276
|
+
export async function readChunkFromSource({ root, path, offset, size, expectedFileSize, expectedChunkSha256, signal, }) {
|
|
277
|
+
checkSignal(signal);
|
|
278
|
+
safePath(path);
|
|
279
|
+
const resolvedRoot = resolve(root);
|
|
280
|
+
await checkChain(resolvedRoot, false, signal);
|
|
281
|
+
const full = join(resolvedRoot, ...path.split("/"));
|
|
282
|
+
if (!within(resolvedRoot, full))
|
|
283
|
+
throw new Error("Target escapes project root");
|
|
284
|
+
await checkChain(full, false, signal);
|
|
285
|
+
const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
286
|
+
try {
|
|
287
|
+
checkSignal(signal);
|
|
288
|
+
const fileStat = await handle.stat();
|
|
289
|
+
if (!fileStat.isFile())
|
|
290
|
+
throw new Error("Target must be a regular file");
|
|
291
|
+
if (Number.isSafeInteger(expectedFileSize) && fileStat.size !== expectedFileSize) {
|
|
292
|
+
throw new Error("Source file modified during transfer: size mismatch");
|
|
293
|
+
}
|
|
294
|
+
const buf = Buffer.alloc(size);
|
|
295
|
+
let bytesRead = 0;
|
|
296
|
+
while (bytesRead < size) {
|
|
297
|
+
checkSignal(signal);
|
|
298
|
+
const res = await handle.read(buf, bytesRead, size - bytesRead, offset + bytesRead);
|
|
299
|
+
if (res.bytesRead === 0)
|
|
300
|
+
break;
|
|
301
|
+
bytesRead += res.bytesRead;
|
|
302
|
+
}
|
|
303
|
+
const actualBuf = bytesRead === size ? buf : buf.subarray(0, bytesRead);
|
|
304
|
+
const actualHash = hash(actualBuf);
|
|
305
|
+
if (typeof expectedChunkSha256 === "string" && actualHash !== expectedChunkSha256) {
|
|
306
|
+
throw new Error("Source file modified during transfer: chunk checksum mismatch");
|
|
307
|
+
}
|
|
308
|
+
return { buffer: actualBuf, sha256: actualHash };
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
await handle.close();
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/** Receiver instance supporting chunked transfer, resume, verification, and staging. */
|
|
315
|
+
export function createChunkedTransferReceiver(config) {
|
|
316
|
+
const root = resolve(config.root);
|
|
317
|
+
const dataDir = resolve(config.dataDir);
|
|
318
|
+
const allowReceive = config.allowReceive === true;
|
|
319
|
+
const storage = join(dataDir, "device-transfers");
|
|
320
|
+
if (within(root, dataDir) || within(root, storage))
|
|
321
|
+
throw new Error("File sync dataDir and transfer storage must be outside the project root");
|
|
322
|
+
const sessions = new Map();
|
|
323
|
+
let totalStagedBytes = 0;
|
|
324
|
+
let closed = false;
|
|
325
|
+
let queue = Promise.resolve();
|
|
326
|
+
function serialized(fn) {
|
|
327
|
+
const result = queue.then(fn);
|
|
328
|
+
queue = result.catch(() => { });
|
|
329
|
+
return result;
|
|
330
|
+
}
|
|
331
|
+
function active(signal) {
|
|
332
|
+
if (closed)
|
|
333
|
+
throw new Error("Transfer receiver is closed");
|
|
334
|
+
checkSignal(signal);
|
|
335
|
+
}
|
|
336
|
+
async function roots(signal) {
|
|
337
|
+
await checkChain(root, false, signal);
|
|
338
|
+
active(signal);
|
|
339
|
+
const stats = await lstat(root);
|
|
340
|
+
if (!stats.isDirectory())
|
|
341
|
+
throw new Error("Project root must be a directory");
|
|
342
|
+
await checkChain(storage, true, signal);
|
|
343
|
+
active(signal);
|
|
344
|
+
const canonical = await realpath(root);
|
|
345
|
+
if (within(canonical, dataDir))
|
|
346
|
+
throw new Error("Unsafe data directory");
|
|
347
|
+
}
|
|
348
|
+
async function target(path, signal) {
|
|
349
|
+
safePath(path);
|
|
350
|
+
await roots(signal);
|
|
351
|
+
active(signal);
|
|
352
|
+
const full = join(root, ...path.split("/"));
|
|
353
|
+
if (!within(root, full))
|
|
354
|
+
throw new Error("Target escapes project root");
|
|
355
|
+
await checkChain(full, true, signal);
|
|
356
|
+
active(signal);
|
|
357
|
+
return full;
|
|
358
|
+
}
|
|
359
|
+
async function readFileSnapshot(path, signal) {
|
|
360
|
+
active(signal);
|
|
361
|
+
const full = await target(path, signal);
|
|
362
|
+
let before;
|
|
363
|
+
try {
|
|
364
|
+
before = await lstat(full);
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
if (missing(e))
|
|
368
|
+
return null;
|
|
369
|
+
throw e;
|
|
370
|
+
}
|
|
371
|
+
if (!before.isFile() || before.nlink > 1)
|
|
372
|
+
throw new Error("Target must be a single-link regular file");
|
|
373
|
+
const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
374
|
+
try {
|
|
375
|
+
active(signal);
|
|
376
|
+
const opened = await handle.stat();
|
|
377
|
+
if (!opened.isFile() || identity(opened) !== identity(before))
|
|
378
|
+
throw new Error("File changed while opening");
|
|
379
|
+
const buf = Buffer.alloc(before.size);
|
|
380
|
+
let totalRead = 0;
|
|
381
|
+
while (totalRead < buf.length) {
|
|
382
|
+
active(signal);
|
|
383
|
+
const r = await handle.read(buf, totalRead, buf.length - totalRead, totalRead);
|
|
384
|
+
if (!r.bytesRead)
|
|
385
|
+
break;
|
|
386
|
+
totalRead += r.bytesRead;
|
|
387
|
+
}
|
|
388
|
+
const after = await handle.stat();
|
|
389
|
+
if (totalRead !== before.size || identity(after) !== identity(before))
|
|
390
|
+
throw new Error("File changed while reading");
|
|
391
|
+
return { bytes: buf, snapshot: { hash: hash(buf), identity: identity(before) } };
|
|
392
|
+
}
|
|
393
|
+
finally {
|
|
394
|
+
await handle.close();
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
async function makePreview(manifest, signal) {
|
|
398
|
+
const baselines = [];
|
|
399
|
+
const files = [];
|
|
400
|
+
for (const entry of manifest.files) {
|
|
401
|
+
const current = await readFileSnapshot(entry.path, signal);
|
|
402
|
+
baselines.push(current?.snapshot ?? null);
|
|
403
|
+
files.push({
|
|
404
|
+
path: entry.path,
|
|
405
|
+
size: entry.size,
|
|
406
|
+
sha256: entry.sha256,
|
|
407
|
+
baseline: current?.snapshot.hash ?? null,
|
|
408
|
+
status: !current ? "create" : current.snapshot.hash === entry.sha256 ? "identical" : "conflict",
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
const revision = hash(JSON.stringify({ id: manifest.transferId, files, baselines }));
|
|
412
|
+
return { preview: { id: manifest.transferId, revision, files }, baselines };
|
|
413
|
+
}
|
|
414
|
+
async function persistState(session) {
|
|
415
|
+
const statePath = join(session.dir, "state.json");
|
|
416
|
+
const tempPath = `${statePath}.${randomUUID()}.tmp`;
|
|
417
|
+
const data = JSON.stringify({
|
|
418
|
+
transferId: session.manifest.transferId,
|
|
419
|
+
status: session.status,
|
|
420
|
+
binding: { canonicalRoot: resolve(config.root) },
|
|
421
|
+
receivedChunks: Array.from(session.receivedChunks),
|
|
422
|
+
chunkHashes: Array.from(session.chunkHashes.entries()),
|
|
423
|
+
receivedBytes: session.receivedBytes,
|
|
424
|
+
filesCompleted: Array.from(session.filesCompleted),
|
|
425
|
+
preview: session.preview,
|
|
426
|
+
error: session.error,
|
|
427
|
+
});
|
|
428
|
+
const handle = await open(tempPath, "wx", 0o600);
|
|
429
|
+
try {
|
|
430
|
+
await handle.writeFile(data);
|
|
431
|
+
await handle.sync();
|
|
432
|
+
}
|
|
433
|
+
finally {
|
|
434
|
+
await handle.close();
|
|
435
|
+
}
|
|
436
|
+
await rename(tempPath, statePath);
|
|
437
|
+
}
|
|
438
|
+
async function readNoFollow(filePath) {
|
|
439
|
+
const handle = await open(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
440
|
+
try {
|
|
441
|
+
const stat = await handle.stat();
|
|
442
|
+
if (!stat.isFile())
|
|
443
|
+
throw new Error("Target is not a regular file");
|
|
444
|
+
const buf = Buffer.alloc(stat.size);
|
|
445
|
+
let total = 0;
|
|
446
|
+
while (total < buf.length) {
|
|
447
|
+
const res = await handle.read(buf, total, buf.length - total, total);
|
|
448
|
+
if (!res.bytesRead)
|
|
449
|
+
break;
|
|
450
|
+
total += res.bytesRead;
|
|
451
|
+
}
|
|
452
|
+
return buf.toString("utf8");
|
|
453
|
+
}
|
|
454
|
+
finally {
|
|
455
|
+
await handle.close();
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/** Scan storage to discover existing persisted sessions on startup for true cross-restart resume.
|
|
459
|
+
* Checks safety chains, validates manifest schema & hashes without following symlinks,
|
|
460
|
+
* verifies receivedChunks against physical files, and checks byte/session budgets. */
|
|
461
|
+
const initializedPromise = (async () => {
|
|
462
|
+
try {
|
|
463
|
+
await checkChain(storage, true);
|
|
464
|
+
const entries = await readdir(storage).catch(() => []);
|
|
465
|
+
for (const name of entries) {
|
|
466
|
+
if (!name.startsWith("transfer-"))
|
|
467
|
+
continue;
|
|
468
|
+
const dir = join(storage, name);
|
|
469
|
+
try {
|
|
470
|
+
await checkChain(dir, false);
|
|
471
|
+
const dirStat = await lstat(dir);
|
|
472
|
+
if (!dirStat.isDirectory() || dirStat.isSymbolicLink()) {
|
|
473
|
+
throw new Error("Invalid transfer directory link");
|
|
474
|
+
}
|
|
475
|
+
const manifestStr = await readNoFollow(join(dir, "manifest.json"));
|
|
476
|
+
const parsedManifest = JSON.parse(manifestStr);
|
|
477
|
+
const manifest = validateChunkedManifest(parsedManifest);
|
|
478
|
+
// Hard binding: dirname must match transferId
|
|
479
|
+
if (name !== `transfer-${manifest.transferId}`) {
|
|
480
|
+
throw new Error("Directory name mismatch for transferId");
|
|
481
|
+
}
|
|
482
|
+
// Reject duplicate transferId directories
|
|
483
|
+
if (sessions.has(manifest.transferId)) {
|
|
484
|
+
throw new Error("Duplicate transferId directory detected");
|
|
485
|
+
}
|
|
486
|
+
const stateStr = await readNoFollow(join(dir, "state.json"));
|
|
487
|
+
const state = JSON.parse(stateStr);
|
|
488
|
+
if (!state || typeof state !== "object")
|
|
489
|
+
throw new Error("Invalid state.json");
|
|
490
|
+
if (state.binding?.canonicalRoot && state.binding.canonicalRoot !== resolve(config.root)) {
|
|
491
|
+
throw new Error("Staged session canonical root mismatch: old bundle on new root denied");
|
|
492
|
+
}
|
|
493
|
+
const receivedChunksArr = Array.isArray(state.receivedChunks) ? state.receivedChunks : [];
|
|
494
|
+
for (const idx of receivedChunksArr) {
|
|
495
|
+
if (!Number.isSafeInteger(idx) || idx < 0 || idx >= manifest.totalChunks) {
|
|
496
|
+
throw new Error("Corrupt receivedChunk index in state");
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const chunkHashesArr = Array.isArray(state.chunkHashes) ? state.chunkHashes : [];
|
|
500
|
+
const chunkHashesMap = new Map();
|
|
501
|
+
for (const entry of chunkHashesArr) {
|
|
502
|
+
if (Array.isArray(entry) && Number.isSafeInteger(entry[0]) && typeof entry[1] === "string") {
|
|
503
|
+
chunkHashesMap.set(entry[0], entry[1]);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const filesDir = join(dir, "files");
|
|
507
|
+
try {
|
|
508
|
+
await checkChain(filesDir, false);
|
|
509
|
+
const filesStat = await lstat(filesDir);
|
|
510
|
+
if (filesStat.isSymbolicLink() || !filesStat.isDirectory()) {
|
|
511
|
+
throw new Error("Invalid staged files directory");
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
catch (e) {
|
|
515
|
+
if (!missing(e))
|
|
516
|
+
throw e;
|
|
517
|
+
}
|
|
518
|
+
const session = {
|
|
519
|
+
manifest,
|
|
520
|
+
dir,
|
|
521
|
+
status: (["staging", "staged", "applied", "cancelled", "failed"].includes(state.status)
|
|
522
|
+
? state.status
|
|
523
|
+
: "staging"),
|
|
524
|
+
receivedChunks: new Set(receivedChunksArr),
|
|
525
|
+
chunkHashes: chunkHashesMap,
|
|
526
|
+
receivedBytes: Number.isSafeInteger(state.receivedBytes) ? state.receivedBytes : 0,
|
|
527
|
+
reservedBytes: manifest.totalBytes,
|
|
528
|
+
filesCompleted: new Set(Array.isArray(state.filesCompleted) ? state.filesCompleted : []),
|
|
529
|
+
preview: state.preview,
|
|
530
|
+
error: typeof state.error === "string" ? state.error : undefined,
|
|
531
|
+
};
|
|
532
|
+
// Check quota limits on restart recovery
|
|
533
|
+
if (sessions.size >= CHUNKED_TRANSFER_LIMITS.maxStagedTransfers ||
|
|
534
|
+
totalStagedBytes + manifest.totalBytes > CHUNKED_TRANSFER_LIMITS.maxStagedBytes) {
|
|
535
|
+
session.status = "failed";
|
|
536
|
+
session.error = "Staging quota exceeded upon restart recovery";
|
|
537
|
+
}
|
|
538
|
+
else {
|
|
539
|
+
totalStagedBytes += manifest.totalBytes;
|
|
540
|
+
}
|
|
541
|
+
sessions.set(manifest.transferId, session);
|
|
542
|
+
}
|
|
543
|
+
catch {
|
|
544
|
+
// Purge corrupt / invalid / symlinked directories safely
|
|
545
|
+
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
catch { }
|
|
550
|
+
})();
|
|
551
|
+
return {
|
|
552
|
+
/** Initialize a chunked transfer session from manifest */
|
|
553
|
+
initTransfer(manifestInput, { signal } = {}) {
|
|
554
|
+
return serialized(async () => {
|
|
555
|
+
await initializedPromise;
|
|
556
|
+
active(signal);
|
|
557
|
+
if (!allowReceive)
|
|
558
|
+
throw new Error("Receiving files is disabled");
|
|
559
|
+
// Hard validation of manifest schema, hash, chunks and offsets
|
|
560
|
+
const manifest = validateChunkedManifest(manifestInput);
|
|
561
|
+
// Check if session already exists for resume
|
|
562
|
+
const existing = sessions.get(manifest.transferId);
|
|
563
|
+
if (existing) {
|
|
564
|
+
if (existing.manifest.manifestHash !== manifest.manifestHash)
|
|
565
|
+
throw new Error("Transfer manifest hash mismatch on resume");
|
|
566
|
+
return {
|
|
567
|
+
transferId: existing.manifest.transferId,
|
|
568
|
+
status: existing.status,
|
|
569
|
+
totalBytes: existing.manifest.totalBytes,
|
|
570
|
+
transferredBytes: existing.receivedBytes,
|
|
571
|
+
totalFiles: existing.manifest.totalFiles,
|
|
572
|
+
completedFiles: existing.filesCompleted.size,
|
|
573
|
+
totalChunks: existing.manifest.totalChunks,
|
|
574
|
+
receivedChunks: Array.from(existing.receivedChunks),
|
|
575
|
+
percent: existing.manifest.totalBytes > 0
|
|
576
|
+
? Math.round((existing.receivedBytes / existing.manifest.totalBytes) * 100)
|
|
577
|
+
: 100,
|
|
578
|
+
preview: existing.preview,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
if (sessions.size >= CHUNKED_TRANSFER_LIMITS.maxStagedTransfers)
|
|
582
|
+
throw new Error("Max staged transfers reached");
|
|
583
|
+
if (totalStagedBytes + manifest.totalBytes > CHUNKED_TRANSFER_LIMITS.maxStagedBytes)
|
|
584
|
+
throw new Error("Staging byte quota exceeded");
|
|
585
|
+
await roots(signal);
|
|
586
|
+
await mkdir(storage, { recursive: true, mode: 0o700 });
|
|
587
|
+
await checkChain(storage, false, signal);
|
|
588
|
+
// Strict sanitized directory name: transfer-<UUID>
|
|
589
|
+
const dir = join(storage, `transfer-${manifest.transferId}`);
|
|
590
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
591
|
+
try {
|
|
592
|
+
const filesDir = join(dir, "files");
|
|
593
|
+
await mkdir(filesDir, { recursive: true, mode: 0o700 });
|
|
594
|
+
const manifestPath = join(dir, "manifest.json");
|
|
595
|
+
const handle = await open(manifestPath, "wx", 0o600);
|
|
596
|
+
try {
|
|
597
|
+
await handle.writeFile(JSON.stringify(manifest));
|
|
598
|
+
await handle.sync();
|
|
599
|
+
}
|
|
600
|
+
finally {
|
|
601
|
+
await handle.close();
|
|
602
|
+
}
|
|
603
|
+
const session = {
|
|
604
|
+
manifest,
|
|
605
|
+
dir,
|
|
606
|
+
status: "staging",
|
|
607
|
+
receivedChunks: new Set(),
|
|
608
|
+
chunkHashes: new Map(),
|
|
609
|
+
receivedBytes: 0,
|
|
610
|
+
reservedBytes: manifest.totalBytes,
|
|
611
|
+
filesCompleted: new Set(),
|
|
612
|
+
};
|
|
613
|
+
await persistState(session);
|
|
614
|
+
totalStagedBytes += manifest.totalBytes;
|
|
615
|
+
sessions.set(manifest.transferId, session);
|
|
616
|
+
return {
|
|
617
|
+
transferId: manifest.transferId,
|
|
618
|
+
status: "staging",
|
|
619
|
+
totalBytes: manifest.totalBytes,
|
|
620
|
+
transferredBytes: 0,
|
|
621
|
+
totalFiles: manifest.totalFiles,
|
|
622
|
+
completedFiles: 0,
|
|
623
|
+
totalChunks: manifest.totalChunks,
|
|
624
|
+
receivedChunks: [],
|
|
625
|
+
percent: 0,
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
catch (err) {
|
|
629
|
+
// Rollback staging and quota on failure
|
|
630
|
+
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
631
|
+
throw err;
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
},
|
|
635
|
+
/** Writes a received chunk into persistent staging.
|
|
636
|
+
* Validates chunk offsets, sizes against manifest, checks chunk hash before decode,
|
|
637
|
+
* and persists state to disk BEFORE updating in-memory progress! */
|
|
638
|
+
writeChunk(chunk, { signal } = {}) {
|
|
639
|
+
return serialized(async () => {
|
|
640
|
+
await initializedPromise;
|
|
641
|
+
active(signal);
|
|
642
|
+
if (!chunk || typeof chunk !== "object")
|
|
643
|
+
throw new Error("Invalid chunk payload");
|
|
644
|
+
if (!isUuid(chunk.transferId))
|
|
645
|
+
throw new Error("Invalid transferId in chunk");
|
|
646
|
+
const session = sessions.get(chunk.transferId);
|
|
647
|
+
if (!session)
|
|
648
|
+
throw new Error("Transfer session not found");
|
|
649
|
+
if (session.status !== "staging")
|
|
650
|
+
throw new Error(`Cannot write chunk in ${session.status} state`);
|
|
651
|
+
if (!Number.isSafeInteger(chunk.chunkIndex) ||
|
|
652
|
+
chunk.chunkIndex < 0 ||
|
|
653
|
+
chunk.chunkIndex >= session.manifest.totalChunks)
|
|
654
|
+
throw new Error("Invalid chunkIndex");
|
|
655
|
+
// Find file entry in manifest
|
|
656
|
+
const fileEntry = session.manifest.files.find((f) => f.path === chunk.path);
|
|
657
|
+
if (!fileEntry)
|
|
658
|
+
throw new Error("Chunk path not in manifest");
|
|
659
|
+
if (chunk.chunkIndex < fileEntry.firstChunkIndex ||
|
|
660
|
+
chunk.chunkIndex >= fileEntry.firstChunkIndex + fileEntry.chunkCount)
|
|
661
|
+
throw new Error("Chunk index out of range for file");
|
|
662
|
+
// Derive expected offset and size from manifest; DO NOT trust client input
|
|
663
|
+
const expectedOffset = (chunk.chunkIndex - fileEntry.firstChunkIndex) * session.manifest.chunkSize;
|
|
664
|
+
const expectedSize = Math.min(session.manifest.chunkSize, fileEntry.size - expectedOffset);
|
|
665
|
+
if (chunk.offset !== expectedOffset)
|
|
666
|
+
throw new Error(`Chunk offset mismatch: expected ${expectedOffset}, got ${chunk.offset}`);
|
|
667
|
+
if (chunk.size !== expectedSize)
|
|
668
|
+
throw new Error(`Chunk size mismatch: expected ${expectedSize}, got ${chunk.size}`);
|
|
669
|
+
if (typeof chunk.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(chunk.sha256))
|
|
670
|
+
throw new Error("Invalid chunk sha256 checksum format");
|
|
671
|
+
// Length check before decoding base64 to prevent unbounded memory allocation
|
|
672
|
+
if (typeof chunk.data !== "string")
|
|
673
|
+
throw new Error("Chunk data must be base64 string");
|
|
674
|
+
const expectedBase64Len = 4 * Math.ceil(expectedSize / 3);
|
|
675
|
+
if (chunk.data.length !== expectedBase64Len)
|
|
676
|
+
throw new Error(`Invalid chunk base64 data length: expected ${expectedBase64Len}, got ${chunk.data.length}`);
|
|
677
|
+
// If already received, verify checksum match
|
|
678
|
+
if (session.receivedChunks.has(chunk.chunkIndex)) {
|
|
679
|
+
const existingHash = session.chunkHashes.get(chunk.chunkIndex);
|
|
680
|
+
if (existingHash !== chunk.sha256)
|
|
681
|
+
throw new Error("Duplicate chunk with mismatched checksum");
|
|
682
|
+
return {
|
|
683
|
+
transferId: session.manifest.transferId,
|
|
684
|
+
status: session.status,
|
|
685
|
+
chunkIndex: chunk.chunkIndex,
|
|
686
|
+
received: true,
|
|
687
|
+
totalBytes: session.manifest.totalBytes,
|
|
688
|
+
transferredBytes: session.receivedBytes,
|
|
689
|
+
totalFiles: session.manifest.totalFiles,
|
|
690
|
+
completedFiles: session.filesCompleted.size,
|
|
691
|
+
totalChunks: session.manifest.totalChunks,
|
|
692
|
+
receivedChunks: Array.from(session.receivedChunks),
|
|
693
|
+
percent: session.manifest.totalBytes > 0
|
|
694
|
+
? Math.round((session.receivedBytes / session.manifest.totalBytes) * 100)
|
|
695
|
+
: 100,
|
|
696
|
+
preview: session.preview,
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
// Decode and verify checksum
|
|
700
|
+
const dataBytes = Buffer.from(chunk.data, "base64");
|
|
701
|
+
if (dataBytes.length !== expectedSize)
|
|
702
|
+
throw new Error("Decoded chunk size mismatch");
|
|
703
|
+
const computedHash = hash(dataBytes);
|
|
704
|
+
if (computedHash !== chunk.sha256)
|
|
705
|
+
throw new Error("Chunk sha256 checksum mismatch");
|
|
706
|
+
// Write to staged file
|
|
707
|
+
const stagedFilePath = join(session.dir, "files", ...fileEntry.path.split("/"));
|
|
708
|
+
await mkdir(dirname(stagedFilePath), { recursive: true, mode: 0o700 });
|
|
709
|
+
const fileHandle = await open(stagedFilePath, constants.O_CREAT | constants.O_RDWR, 0o600);
|
|
710
|
+
try {
|
|
711
|
+
active(signal);
|
|
712
|
+
await fileHandle.write(dataBytes, 0, dataBytes.length, expectedOffset);
|
|
713
|
+
await fileHandle.sync();
|
|
714
|
+
}
|
|
715
|
+
finally {
|
|
716
|
+
await fileHandle.close();
|
|
717
|
+
}
|
|
718
|
+
// Check if this file has completed all its chunks
|
|
719
|
+
let fileFinished = true;
|
|
720
|
+
for (let i = fileEntry.firstChunkIndex; i < fileEntry.firstChunkIndex + fileEntry.chunkCount; i++) {
|
|
721
|
+
if (i !== chunk.chunkIndex && !session.receivedChunks.has(i)) {
|
|
722
|
+
fileFinished = false;
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
if (fileFinished) {
|
|
727
|
+
// Verify entire file hash
|
|
728
|
+
const checkHandle = await open(stagedFilePath, constants.O_RDONLY);
|
|
729
|
+
const fileHasher = createHash("sha256");
|
|
730
|
+
try {
|
|
731
|
+
const buf = Buffer.alloc(64 * 1024);
|
|
732
|
+
let bytesRead = 0;
|
|
733
|
+
let totalRead = 0;
|
|
734
|
+
while ((bytesRead = (await checkHandle.read(buf, 0, buf.length, totalRead)).bytesRead) > 0) {
|
|
735
|
+
active(signal);
|
|
736
|
+
fileHasher.update(buf.subarray(0, bytesRead));
|
|
737
|
+
totalRead += bytesRead;
|
|
738
|
+
}
|
|
739
|
+
if (totalRead !== fileEntry.size)
|
|
740
|
+
throw new Error("Staged file size mismatch");
|
|
741
|
+
const fileHash = fileHasher.digest("hex");
|
|
742
|
+
if (fileHash !== fileEntry.sha256)
|
|
743
|
+
throw new Error("Staged file sha256 checksum mismatch");
|
|
744
|
+
}
|
|
745
|
+
finally {
|
|
746
|
+
await checkHandle.close();
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
// Persist state to disk BEFORE publishing to in-memory progress!
|
|
750
|
+
const nextReceivedChunks = new Set(session.receivedChunks);
|
|
751
|
+
nextReceivedChunks.add(chunk.chunkIndex);
|
|
752
|
+
const nextChunkHashes = new Map(session.chunkHashes);
|
|
753
|
+
nextChunkHashes.set(chunk.chunkIndex, chunk.sha256);
|
|
754
|
+
const nextFilesCompleted = new Set(session.filesCompleted);
|
|
755
|
+
if (fileFinished)
|
|
756
|
+
nextFilesCompleted.add(fileEntry.path);
|
|
757
|
+
let nextStatus = session.status;
|
|
758
|
+
let nextPreview = session.preview;
|
|
759
|
+
let nextBaselines = session.baselines;
|
|
760
|
+
if (nextReceivedChunks.size === session.manifest.totalChunks) {
|
|
761
|
+
// All chunks completed! Build preview
|
|
762
|
+
const { preview, baselines } = await makePreview(session.manifest, signal);
|
|
763
|
+
nextPreview = preview;
|
|
764
|
+
nextBaselines = baselines;
|
|
765
|
+
nextStatus = "staged";
|
|
766
|
+
}
|
|
767
|
+
// Write state to disk
|
|
768
|
+
const tempSession = {
|
|
769
|
+
...session,
|
|
770
|
+
receivedChunks: nextReceivedChunks,
|
|
771
|
+
chunkHashes: nextChunkHashes,
|
|
772
|
+
receivedBytes: session.receivedBytes + dataBytes.length,
|
|
773
|
+
filesCompleted: nextFilesCompleted,
|
|
774
|
+
status: nextStatus,
|
|
775
|
+
preview: nextPreview,
|
|
776
|
+
};
|
|
777
|
+
await persistState(tempSession);
|
|
778
|
+
// Disk state persisted successfully, now safely update in-memory session!
|
|
779
|
+
session.receivedChunks = nextReceivedChunks;
|
|
780
|
+
session.chunkHashes = nextChunkHashes;
|
|
781
|
+
session.receivedBytes = tempSession.receivedBytes;
|
|
782
|
+
session.filesCompleted = nextFilesCompleted;
|
|
783
|
+
session.status = nextStatus;
|
|
784
|
+
session.preview = nextPreview;
|
|
785
|
+
session.baselines = nextBaselines;
|
|
786
|
+
return {
|
|
787
|
+
transferId: session.manifest.transferId,
|
|
788
|
+
status: session.status,
|
|
789
|
+
chunkIndex: chunk.chunkIndex,
|
|
790
|
+
received: true,
|
|
791
|
+
totalBytes: session.manifest.totalBytes,
|
|
792
|
+
transferredBytes: session.receivedBytes,
|
|
793
|
+
totalFiles: session.manifest.totalFiles,
|
|
794
|
+
completedFiles: session.filesCompleted.size,
|
|
795
|
+
totalChunks: session.manifest.totalChunks,
|
|
796
|
+
receivedChunks: Array.from(session.receivedChunks),
|
|
797
|
+
percent: session.manifest.totalBytes > 0
|
|
798
|
+
? Math.round((session.receivedBytes / session.manifest.totalBytes) * 100)
|
|
799
|
+
: 100,
|
|
800
|
+
preview: session.preview,
|
|
801
|
+
};
|
|
802
|
+
});
|
|
803
|
+
},
|
|
804
|
+
/** Query status for resume / progress tracking */
|
|
805
|
+
getStatus(transferId) {
|
|
806
|
+
return serialized(async () => {
|
|
807
|
+
await initializedPromise;
|
|
808
|
+
const session = sessions.get(transferId);
|
|
809
|
+
if (!session)
|
|
810
|
+
throw new Error("Transfer session not found");
|
|
811
|
+
return {
|
|
812
|
+
transferId: session.manifest.transferId,
|
|
813
|
+
status: session.status,
|
|
814
|
+
totalBytes: session.manifest.totalBytes,
|
|
815
|
+
transferredBytes: session.receivedBytes,
|
|
816
|
+
totalFiles: session.manifest.totalFiles,
|
|
817
|
+
completedFiles: session.filesCompleted.size,
|
|
818
|
+
totalChunks: session.manifest.totalChunks,
|
|
819
|
+
receivedChunks: Array.from(session.receivedChunks),
|
|
820
|
+
percent: session.manifest.totalBytes > 0
|
|
821
|
+
? Math.round((session.receivedBytes / session.manifest.totalBytes) * 100)
|
|
822
|
+
: 100,
|
|
823
|
+
error: session.error,
|
|
824
|
+
preview: session.preview,
|
|
825
|
+
};
|
|
826
|
+
});
|
|
827
|
+
},
|
|
828
|
+
/** Paginated file listing from manifest */
|
|
829
|
+
getFilePage(transferId, page = 1, pageSize = 100) {
|
|
830
|
+
return serialized(async () => {
|
|
831
|
+
await initializedPromise;
|
|
832
|
+
const session = sessions.get(transferId);
|
|
833
|
+
if (!session)
|
|
834
|
+
throw new Error("Transfer session not found");
|
|
835
|
+
const totalFiles = session.manifest.totalFiles;
|
|
836
|
+
const validPage = Math.max(1, page);
|
|
837
|
+
const validPageSize = Math.min(200, Math.max(1, pageSize));
|
|
838
|
+
const totalPages = Math.max(1, Math.ceil(totalFiles / validPageSize));
|
|
839
|
+
const start = (validPage - 1) * validPageSize;
|
|
840
|
+
const files = session.manifest.files.slice(start, start + validPageSize);
|
|
841
|
+
return {
|
|
842
|
+
files,
|
|
843
|
+
totalFiles,
|
|
844
|
+
page: validPage,
|
|
845
|
+
totalPages,
|
|
846
|
+
truncated: totalFiles > validPageSize,
|
|
847
|
+
};
|
|
848
|
+
});
|
|
849
|
+
},
|
|
850
|
+
/** Abort/cancel transfer. Quota is only returned AFTER physical disk IO cleanup completes! */
|
|
851
|
+
abortTransfer(transferId) {
|
|
852
|
+
return serialized(async () => {
|
|
853
|
+
await initializedPromise;
|
|
854
|
+
const session = sessions.get(transferId);
|
|
855
|
+
if (!session)
|
|
856
|
+
return { ok: true };
|
|
857
|
+
session.status = "cancelled";
|
|
858
|
+
if (session.cleanupPromise) {
|
|
859
|
+
await session.cleanupPromise;
|
|
860
|
+
return { ok: true };
|
|
861
|
+
}
|
|
862
|
+
// Physical cleanup must finish BEFORE returning quota!
|
|
863
|
+
const cleanup = (async () => {
|
|
864
|
+
try {
|
|
865
|
+
await checkChain(session.dir);
|
|
866
|
+
await rm(session.dir, { recursive: true, force: true });
|
|
867
|
+
}
|
|
868
|
+
catch {
|
|
869
|
+
}
|
|
870
|
+
finally {
|
|
871
|
+
// ONLY return staged quota after physical IO release!
|
|
872
|
+
totalStagedBytes = Math.max(0, totalStagedBytes - session.reservedBytes);
|
|
873
|
+
sessions.delete(transferId);
|
|
874
|
+
}
|
|
875
|
+
})();
|
|
876
|
+
session.cleanupPromise = cleanup;
|
|
877
|
+
await cleanup;
|
|
878
|
+
return { ok: true };
|
|
879
|
+
});
|
|
880
|
+
},
|
|
881
|
+
/** Preview a staged chunked transfer */
|
|
882
|
+
preview(transferId, { signal } = {}) {
|
|
883
|
+
return serialized(async () => {
|
|
884
|
+
await initializedPromise;
|
|
885
|
+
active(signal);
|
|
886
|
+
const session = sessions.get(transferId);
|
|
887
|
+
if (!session)
|
|
888
|
+
throw new Error("Transfer session not found");
|
|
889
|
+
if (session.status !== "staged" && session.status !== "staging")
|
|
890
|
+
throw new Error(`Cannot preview in ${session.status} state`);
|
|
891
|
+
if (!session.preview) {
|
|
892
|
+
const { preview, baselines } = await makePreview(session.manifest, signal);
|
|
893
|
+
session.preview = preview;
|
|
894
|
+
session.baselines = baselines;
|
|
895
|
+
}
|
|
896
|
+
return structuredClone(session.preview);
|
|
897
|
+
});
|
|
898
|
+
},
|
|
899
|
+
/** Apply staged chunked files with explicit decisions using shared atomic metadata-preserving save */
|
|
900
|
+
apply({ transferId, revision, decisions = {}, signal, }) {
|
|
901
|
+
return serialized(async () => {
|
|
902
|
+
await initializedPromise;
|
|
903
|
+
active(signal);
|
|
904
|
+
if (!allowReceive)
|
|
905
|
+
throw new Error("Receiving files is disabled");
|
|
906
|
+
const session = sessions.get(transferId);
|
|
907
|
+
if (!session)
|
|
908
|
+
throw new Error("Transfer session not found");
|
|
909
|
+
if (session.status !== "staged")
|
|
910
|
+
throw new Error("Transfer is not in staged state");
|
|
911
|
+
if (!session.preview || session.preview.revision !== revision)
|
|
912
|
+
throw new Error("Preview revision mismatch");
|
|
913
|
+
for (const [path, decision] of Object.entries(decisions)) {
|
|
914
|
+
if (!session.manifest.files.some((f) => f.path === path) || !["overwrite", "skip"].includes(decision))
|
|
915
|
+
throw new Error("Invalid overwrite decision");
|
|
916
|
+
}
|
|
917
|
+
const report = { id: transferId, applied: [], unchanged: [], rejected: [] };
|
|
918
|
+
for (let i = 0; i < session.manifest.files.length; i++) {
|
|
919
|
+
active(signal);
|
|
920
|
+
const fileEntry = session.manifest.files[i];
|
|
921
|
+
const previewEntry = session.preview.files[i];
|
|
922
|
+
const baseline = session.baselines?.[i] ?? null;
|
|
923
|
+
if (previewEntry.status === "identical") {
|
|
924
|
+
report.unchanged.push(fileEntry.path);
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
const decision = decisions[fileEntry.path];
|
|
928
|
+
if (previewEntry.status === "conflict" && decision !== "overwrite") {
|
|
929
|
+
report.rejected.push({ path: fileEntry.path, reason: "Conflict not authorized for overwrite" });
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
const stagedFilePath = join(session.dir, "files", ...fileEntry.path.split("/"));
|
|
933
|
+
const stagedBuf = await (async () => {
|
|
934
|
+
const h = await open(stagedFilePath, constants.O_RDONLY);
|
|
935
|
+
try {
|
|
936
|
+
const buf = Buffer.alloc(fileEntry.size);
|
|
937
|
+
let r = 0;
|
|
938
|
+
while (r < buf.length) {
|
|
939
|
+
const readRes = await h.read(buf, r, buf.length - r, r);
|
|
940
|
+
if (!readRes.bytesRead)
|
|
941
|
+
break;
|
|
942
|
+
r += readRes.bytesRead;
|
|
943
|
+
}
|
|
944
|
+
return buf;
|
|
945
|
+
}
|
|
946
|
+
finally {
|
|
947
|
+
await h.close();
|
|
948
|
+
}
|
|
949
|
+
})();
|
|
950
|
+
try {
|
|
951
|
+
const current = await readFileSnapshot(fileEntry.path, signal);
|
|
952
|
+
if (!current) {
|
|
953
|
+
// New file creation
|
|
954
|
+
const full = await target(fileEntry.path, signal);
|
|
955
|
+
await mkdir(dirname(full), { recursive: true, mode: 0o700 });
|
|
956
|
+
const h = await open(full, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
|
|
957
|
+
try {
|
|
958
|
+
await h.writeFile(stagedBuf);
|
|
959
|
+
await h.sync();
|
|
960
|
+
}
|
|
961
|
+
finally {
|
|
962
|
+
await h.close();
|
|
963
|
+
}
|
|
964
|
+
report.applied.push(fileEntry.path);
|
|
965
|
+
}
|
|
966
|
+
else {
|
|
967
|
+
// Existing file overwrite with metadata preservation using shared implementation
|
|
968
|
+
const full = await target(fileEntry.path, signal);
|
|
969
|
+
await saveBytesPreservingMetadata({
|
|
970
|
+
path: full,
|
|
971
|
+
bytes: stagedBuf,
|
|
972
|
+
baseline,
|
|
973
|
+
signal,
|
|
974
|
+
});
|
|
975
|
+
report.applied.push(fileEntry.path);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
catch (err) {
|
|
979
|
+
report.rejected.push({ path: fileEntry.path, reason: err.message });
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
session.status = "applied";
|
|
983
|
+
await persistState(session);
|
|
984
|
+
// Physical cleanup after successful apply, then release quota
|
|
985
|
+
try {
|
|
986
|
+
await checkChain(session.dir);
|
|
987
|
+
await rm(session.dir, { recursive: true, force: true });
|
|
988
|
+
}
|
|
989
|
+
catch (e) {
|
|
990
|
+
report.cleanupError = e.message;
|
|
991
|
+
}
|
|
992
|
+
finally {
|
|
993
|
+
totalStagedBytes = Math.max(0, totalStagedBytes - session.reservedBytes);
|
|
994
|
+
sessions.delete(transferId);
|
|
995
|
+
}
|
|
996
|
+
return report;
|
|
997
|
+
});
|
|
998
|
+
},
|
|
999
|
+
async close() {
|
|
1000
|
+
closed = true;
|
|
1001
|
+
await queue;
|
|
1002
|
+
sessions.clear();
|
|
1003
|
+
totalStagedBytes = 0;
|
|
1004
|
+
},
|
|
1005
|
+
};
|
|
1006
|
+
}
|