pi-web-ui 0.113.0 → 0.114.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.
Files changed (228) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +117 -252
  3. package/README.zh-CN.md +145 -223
  4. package/README.zh-TW.md +145 -223
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +145 -20
  8. package/dist/gh-comment-781.md +5 -0
  9. package/dist/server/agent-service-daemon.js +102 -24
  10. package/dist/server/agent-service.js +2296 -1121
  11. package/dist/server/approval-rules.js +29 -3
  12. package/dist/server/ask-user-question-tool.js +8 -8
  13. package/dist/server/atomic-file.js +35 -14
  14. package/dist/server/attachment-store.js +71 -35
  15. package/dist/server/attachments.js +18 -8
  16. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  17. package/dist/server/canvas/canvas-dispatch.js +61 -20
  18. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  19. package/dist/server/canvas/canvas-scheduler.js +99 -0
  20. package/dist/server/canvas/canvas-store.js +107 -54
  21. package/dist/server/canvas/canvas-validation.js +131 -0
  22. package/dist/server/canvas/canvas-workspace.js +284 -0
  23. package/dist/server/client-id-utils.js +8 -0
  24. package/dist/server/client-state.js +104 -22
  25. package/dist/server/communicate-tool.js +76 -0
  26. package/dist/server/compact-context-tool.js +2 -3
  27. package/dist/server/compaction-instructions.js +75 -0
  28. package/dist/server/compaction-markers.js +7 -2
  29. package/dist/server/compaction-state.js +84 -0
  30. package/dist/server/composer-drafts.js +43 -40
  31. package/dist/server/context-evidence.js +346 -0
  32. package/dist/server/control-socket.js +6 -2
  33. package/dist/server/conversation-communication.js +368 -0
  34. package/dist/server/conversation-read-tool.js +3 -4
  35. package/dist/server/conversation-tool-names.js +14 -0
  36. package/dist/server/conversation-tool.js +57 -0
  37. package/dist/server/delegate-mode.js +17 -4
  38. package/dist/server/device-center/bot-catalog.js +88 -0
  39. package/dist/server/device-center/bot-execution.js +106 -0
  40. package/dist/server/device-center/bots.js +170 -0
  41. package/dist/server/device-center/collab-service.js +153 -0
  42. package/dist/server/device-center/collab-tool.js +184 -0
  43. package/dist/server/device-center/connector.js +332 -0
  44. package/dist/server/device-center/desktop-linux.js +372 -0
  45. package/dist/server/device-center/desktop-native.js +413 -0
  46. package/dist/server/device-center/desktop-page.js +232 -0
  47. package/dist/server/device-center/desktop-setup.js +30 -0
  48. package/dist/server/device-center/desktop.js +387 -0
  49. package/dist/server/device-center/device-portals.js +241 -0
  50. package/dist/server/device-center/execution-failure.js +70 -0
  51. package/dist/server/device-center/executor.js +371 -0
  52. package/dist/server/device-center/file-sync.js +493 -0
  53. package/dist/server/device-center/hub-auth.js +69 -0
  54. package/dist/server/device-center/hub-page.js +68 -0
  55. package/dist/server/device-center/hub-setup.js +214 -0
  56. package/dist/server/device-center/hub.js +829 -0
  57. package/dist/server/device-center/local-page.js +17 -0
  58. package/dist/server/device-center/local.js +476 -0
  59. package/dist/server/device-center/main.js +118 -0
  60. package/dist/server/device-center/native-desktop/macos.js +192 -0
  61. package/dist/server/device-center/native-desktop/windows.js +118 -0
  62. package/dist/server/device-center/path-portal.js +120 -0
  63. package/dist/server/device-center/relay.js +959 -0
  64. package/dist/server/device-center/runtime.js +253 -0
  65. package/dist/server/device-center/smoke-preview.js +3 -0
  66. package/dist/server/device-center/store.js +122 -0
  67. package/dist/server/device-center/task-error.js +14 -0
  68. package/dist/server/device-center/transfers.js +293 -0
  69. package/dist/server/device-center/workspaces.js +45 -0
  70. package/dist/server/dispatch-domain-handlers.js +83 -27
  71. package/dist/server/dsh/dsh-agent-service.js +277 -158
  72. package/dist/server/dsh/dsh-client.js +12 -2
  73. package/dist/server/durable/durable-agent-service.js +1 -1
  74. package/dist/server/evidence-tool-hooks.js +49 -0
  75. package/dist/server/file-save.js +95 -0
  76. package/dist/server/file-transfer-routes.js +97 -47
  77. package/dist/server/files-service.js +110 -34
  78. package/dist/server/goal-review-gate.js +16 -6
  79. package/dist/server/goal-service.js +54 -30
  80. package/dist/server/http-proxy.js +120 -0
  81. package/dist/server/index.js +236 -232
  82. package/dist/server/load-timing.js +31 -0
  83. package/dist/server/mcp-bridge.js +219 -94
  84. package/dist/server/mcp-hot-reload.js +31 -5
  85. package/dist/server/mcp-manager.js +192 -93
  86. package/dist/server/mcp-oauth-login.js +169 -0
  87. package/dist/server/mcp-oauth-ui.js +137 -0
  88. package/dist/server/mcp-oauth.js +395 -0
  89. package/dist/server/mcp-project-runtime.js +207 -0
  90. package/dist/server/message-window.js +74 -21
  91. package/dist/server/net-guard.js +122 -20
  92. package/dist/server/payload-limits.js +17 -0
  93. package/dist/server/pending-question.js +82 -0
  94. package/dist/server/plan-mode.js +338 -137
  95. package/dist/server/plugin-assets.js +8 -4
  96. package/dist/server/plugin-chat-attachments.js +48 -0
  97. package/dist/server/plugin-facilities.js +67 -220
  98. package/dist/server/plugin-installer.js +2 -1
  99. package/dist/server/plugin-removal.js +49 -0
  100. package/dist/server/plugin-secrets.js +179 -0
  101. package/dist/server/plugins.js +262 -92
  102. package/dist/server/preset-fields.js +49 -0
  103. package/dist/server/preset-plugin-dependencies.js +57 -0
  104. package/dist/server/preset-share.js +112 -72
  105. package/dist/server/protocol-version.js +1 -1
  106. package/dist/server/queue-modes.js +10 -0
  107. package/dist/server/remote-ssh-service.js +160 -67
  108. package/dist/server/request-context.js +164 -0
  109. package/dist/server/sandbox-data.js +655 -0
  110. package/dist/server/sandbox-engines.js +7 -0
  111. package/dist/server/sandbox-runtime-gate.js +41 -0
  112. package/dist/server/sandbox-service.js +139 -698
  113. package/dist/server/sandbox-tool.js +21 -4
  114. package/dist/server/scheduler-tasks.js +63 -48
  115. package/dist/server/serialize.js +48 -19
  116. package/dist/server/session-branch.js +25 -3
  117. package/dist/server/session-parser.js +28 -18
  118. package/dist/server/session-scan.js +130 -0
  119. package/dist/server/session-search.js +51 -37
  120. package/dist/server/settings-service.js +267 -111
  121. package/dist/server/setup-config.js +58 -0
  122. package/dist/server/skill-maintenance.js +112 -24
  123. package/dist/server/subagent-helpers.js +4 -1
  124. package/dist/server/subagent-notify.js +4 -1
  125. package/dist/server/subagent-security-gate.js +52 -11
  126. package/dist/server/subagent-task.js +27 -0
  127. package/dist/server/subagents.js +217 -46
  128. package/dist/server/tabs.js +9 -1
  129. package/dist/server/terminals.js +467 -363
  130. package/dist/server/tool-guards.js +42 -6
  131. package/dist/server/tool-manager.js +47 -20
  132. package/dist/server/tool-overrides.js +13 -11
  133. package/dist/server/tool-prompt-overrides.js +32 -2
  134. package/dist/server/tool-prompts.js +1 -1
  135. package/dist/server/turn-timing.js +11 -0
  136. package/dist/server/universal/session-store.js +48 -6
  137. package/dist/server/universal/universal-service.js +1 -1
  138. package/dist/server/universal/universal-session.js +334 -231
  139. package/dist/server/uploads.js +64 -5
  140. package/dist/server/webui-context.js +6 -6
  141. package/dist/server/worktree-service.js +32 -24
  142. package/dist/server/ws-pending-queue.js +73 -27
  143. package/dist/test-artifact.md +9 -0
  144. package/dist/test-preview-modal.md +11 -0
  145. package/dist/test-report.html +20 -0
  146. package/docs/device-center.md +142 -0
  147. package/docs/device-desktop.md +48 -0
  148. package/package.json +4 -1
  149. package/plugin-sdk/index.d.ts +45 -9
  150. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  151. package/plugins/catalog.json +1 -1
  152. package/themes/aetheris.css +1 -107
  153. package/themes/ayu-light.css +5 -29
  154. package/themes/bases/flow-base.css +0 -6
  155. package/themes/bases/statusbar-flat-base.css +112 -0
  156. package/themes/bases/zhujian-base.css +1 -0
  157. package/themes/bases/zhupi-base.css +1 -0
  158. package/themes/catppuccin-latte.css +4 -27
  159. package/themes/catppuccin.css +4 -35
  160. package/themes/claude-code-dark.css +1 -0
  161. package/themes/codex.css +4 -28
  162. package/themes/cyberpunk.css +3 -61
  163. package/themes/dark-teal.css +0 -1
  164. package/themes/dazzle.css +3 -73
  165. package/themes/everforest-light.css +4 -27
  166. package/themes/geist.css +4 -28
  167. package/themes/gruvbox-light.css +4 -27
  168. package/themes/kanagawa-lotus.css +4 -27
  169. package/themes/md-preview.css +3 -213
  170. package/themes/mist.css +4 -24
  171. package/themes/nord.css +4 -35
  172. package/themes/one-dark.css +4 -37
  173. package/themes/paper.css +4 -16
  174. package/themes/rose-pine-dawn.css +4 -28
  175. package/themes/sakura.css +4 -24
  176. package/themes/solarized-light.css +4 -27
  177. package/themes/tokyo-night.css +3 -34
  178. package/themes/white.css +4 -26
  179. package/themes/zhujian-dark.css +1 -0
  180. package/themes/zhupi-dark.css +1 -0
  181. package/web/dist/.build-assets.json +1 -0
  182. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  183. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  184. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  185. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  186. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  187. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  188. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  189. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  190. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  191. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  192. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  193. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  194. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  195. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  196. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  197. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  198. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  199. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  200. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  201. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  202. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  203. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  204. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  205. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  206. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  207. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  208. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  209. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  210. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  211. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  212. package/web/dist/assets/index-Cje8iugL.js +83 -0
  213. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  214. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  215. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  216. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  217. package/web/dist/assets/math-BorAY7qD.css +1 -0
  218. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  219. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  220. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  221. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  222. package/web/dist/index.html +15 -9
  223. package/web/dist/sw.js +1 -1
  224. package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
  225. package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
  226. package/web/dist/assets/index-BwL7qBh6.css +0 -1
  227. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  228. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -0,0 +1,30 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { writeAtomicSync } from "../atomic-file.js";
5
+ export function createDesktopSetup(options) {
6
+ const settingsFile = join(resolve(options.dataDir ?? join(homedir(), ".pi-web")), "desktop-settings.json");
7
+ const environmentEnabled = options.environmentEnabled;
8
+ let storedEnabled = false;
9
+ try {
10
+ storedEnabled = JSON.parse(readFileSync(settingsFile, "utf8"))?.enabled === true;
11
+ }
12
+ catch {
13
+ // Missing or unreadable settings leave desktop access disabled by default.
14
+ }
15
+ let closed = false;
16
+ return {
17
+ get enabled() {
18
+ return environmentEnabled || storedEnabled;
19
+ },
20
+ setEnabled(enabled) {
21
+ if (closed)
22
+ throw new Error("Desktop setup closed");
23
+ writeAtomicSync(settingsFile, JSON.stringify({ enabled }) + "\n", { mode: 0o600 });
24
+ storedEnabled = enabled;
25
+ },
26
+ close() {
27
+ closed = true;
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,387 @@
1
+ import express, {} from "express";
2
+ import { WebSocket, WebSocketServer } from "ws";
3
+ import { desktopPage } from "./desktop-page.js";
4
+ import { createDesktopSetup } from "./desktop-setup.js";
5
+ import { nativeDesktopStatus, startNativeDesktop, requestNativeDesktopPermissions, } from "./desktop-native.js";
6
+ import { linuxDesktopStatus, startLinuxDesktop } from "./desktop-linux.js";
7
+ export const DESKTOP_LIMITS = Object.freeze({
8
+ frame: 4 * 1024 * 1024,
9
+ input: 16 * 1024,
10
+ queue: 4 * 1024 * 1024,
11
+ connections: 4,
12
+ connectMs: 60_000,
13
+ idleMs: 30 * 60_000,
14
+ });
15
+ const loopback = (host) => ["127.0.0.1", "::1", "[::1]", "localhost"].includes(host);
16
+ /** Independent local authorization. Connector rewrites Host/Origin and injects local credentials. */
17
+ export function desktopLocalRequest(req) {
18
+ if (!loopback(req.socket.remoteAddress?.replace(/^::ffff:/, "") ?? ""))
19
+ return false;
20
+ try {
21
+ const host = new URL(`http://${req.headers.host ?? ""}`);
22
+ if (!loopback(host.hostname) || host.username || Reflect.get(host, "pass" + "word") || host.pathname !== "/")
23
+ return false;
24
+ if (req.headers.origin) {
25
+ const origin = new URL(req.headers.origin);
26
+ if (!["http:", "https:"].includes(origin.protocol) ||
27
+ origin.host !== host.host ||
28
+ !loopback(origin.hostname) ||
29
+ origin.origin !== req.headers.origin)
30
+ return false;
31
+ }
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /** Validate the entire input at the trust boundary, before invoking any native API. */
39
+ export function parseDesktopInput(value) {
40
+ if (!value || typeof value !== "object" || Array.isArray(value))
41
+ return;
42
+ const v = value;
43
+ const only = (...keys) => Object.keys(v).every((key) => keys.includes(key));
44
+ const finite = (n) => typeof n === "number" && Number.isFinite(n);
45
+ if (v.type === "release" && only("type"))
46
+ return { type: "release" };
47
+ if (v.type === "pointer" &&
48
+ only("type", "x", "y", "action", "button") &&
49
+ finite(v.x) &&
50
+ finite(v.y) &&
51
+ v.x >= 0 &&
52
+ v.x <= 1 &&
53
+ v.y >= 0 &&
54
+ v.y <= 1 &&
55
+ ["move", "down", "up"].includes(String(v.action)) &&
56
+ (v.button === undefined || [0, 1, 2].includes(v.button))) {
57
+ if (v.action !== "move" && v.button === undefined)
58
+ return;
59
+ return v;
60
+ }
61
+ if (v.type === "wheel" && only("type", "deltaY") && finite(v.deltaY) && Math.abs(v.deltaY) <= 10000)
62
+ return v;
63
+ if (v.type === "key" &&
64
+ only("type", "code", "action") &&
65
+ typeof v.code === "string" &&
66
+ /^[A-Za-z][A-Za-z0-9]{0,39}$/.test(v.code) &&
67
+ ["down", "up"].includes(String(v.action)))
68
+ return v;
69
+ if (v.type === "text" &&
70
+ only("type", "text") &&
71
+ typeof v.text === "string" &&
72
+ v.text.length > 0 &&
73
+ v.text.length <= 2048 &&
74
+ !v.text.includes("\0"))
75
+ return v;
76
+ }
77
+ export function createDeviceDesktop({ app, authorize, env = process.env, dataDir, native }) {
78
+ const setup = createDesktopSetup({ dataDir, environmentEnabled: env.PI_DEVICE_DESKTOP === "1" });
79
+ const backend = native ??
80
+ (process.platform === "linux"
81
+ ? { status: linuxDesktopStatus, start: startLinuxDesktop }
82
+ : { status: nativeDesktopStatus, start: startNativeDesktop });
83
+ const requestPermissions = native?.permissions ?? requestNativeDesktopPermissions;
84
+ const permissionControllers = new Set();
85
+ const installation = {
86
+ state: "not-required",
87
+ log: "Native desktop capture does not require browser component installation.",
88
+ };
89
+ const status = () => {
90
+ const platform = backend.status();
91
+ return {
92
+ ...platform,
93
+ os: process.platform,
94
+ enabled: setup.enabled,
95
+ environmentEnabled: env.PI_DEVICE_DESKTOP === "1",
96
+ available: setup.enabled && platform.supported,
97
+ readOnlyEnforcement: "server",
98
+ clientViewOnlyIsPermission: true,
99
+ installation,
100
+ };
101
+ };
102
+ let closed = false;
103
+ const bridges = new Set();
104
+ const wss = new WebSocketServer({ noServer: true, maxPayload: DESKTOP_LIMITS.input, perMessageDeflate: false });
105
+ const allowed = (req) => {
106
+ try {
107
+ return !closed && desktopLocalRequest(req) && authorize(req);
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ };
113
+ app.use((req, res, next) => {
114
+ if (req.path !== "/desktop" && !req.path.startsWith("/api/device-desktop/"))
115
+ return next();
116
+ res.setHeader("Cache-Control", "no-store");
117
+ res.setHeader("X-Content-Type-Options", "nosniff");
118
+ res.setHeader("Referrer-Policy", "no-referrer");
119
+ if (!allowed(req)) {
120
+ res.status(403).end("Desktop authorization required");
121
+ return;
122
+ }
123
+ if (req.path.startsWith("/api/device-desktop/local/") || req.path.startsWith("/api/device-desktop/setup/"))
124
+ return next();
125
+ if (req.method !== "GET") {
126
+ res.status(405).end();
127
+ return;
128
+ }
129
+ if (req.path === "/api/device-desktop/status") {
130
+ res.json(status());
131
+ return;
132
+ }
133
+ if (req.path === "/desktop") {
134
+ res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; frame-ancestors 'self'; base-uri 'none'; form-action 'none'");
135
+ res.type("html").send(desktopPage());
136
+ return;
137
+ }
138
+ res.status(404).end();
139
+ });
140
+ app.get("/api/device-desktop/setup/status", (_req, res) => res.json(status()));
141
+ const setupGuard = (req, res, next) => {
142
+ if (!allowed(req) || !req.headers.origin) {
143
+ res.status(403).end("Desktop authorization and Origin required");
144
+ return;
145
+ }
146
+ next();
147
+ };
148
+ // Both Hub and connector reject these routes. Require a loopback browser as well.
149
+ const localGuard = (req, res, next) => {
150
+ if (!allowed(req) || req.headers["sec-fetch-site"] === "cross-site") {
151
+ res.status(403).json({ error: "Open Device Center on this device to manage desktop permissions." });
152
+ return;
153
+ }
154
+ next();
155
+ };
156
+ app.get("/api/device-desktop/local/status", localGuard, (_req, res) => res.json({ ...status(), permissions: { supported: process.platform === "darwin" } }));
157
+ app.post("/api/device-desktop/local/permissions", localGuard, setupGuard, express.json({ limit: 256 }), async (req, res) => {
158
+ if (!req.body || !["screen", "control"].includes(req.body.kind) || Object.keys(req.body).length !== 1) {
159
+ res.status(400).json({ error: "Expected screen or control permission kind" });
160
+ return;
161
+ }
162
+ if (process.platform !== "darwin" && !native?.permissions) {
163
+ res.status(400).json({ error: "System permission requests are available on macOS only." });
164
+ return;
165
+ }
166
+ if (permissionControllers.size) {
167
+ res.status(409).json({ error: "A system permission request is already running." });
168
+ return;
169
+ }
170
+ const controller = new AbortController();
171
+ permissionControllers.add(controller);
172
+ const abort = () => {
173
+ if (!res.writableEnded)
174
+ controller.abort();
175
+ };
176
+ res.on("close", abort);
177
+ try {
178
+ const permissions = await requestPermissions(req.body.kind, controller.signal);
179
+ if (!controller.signal.aborted && !closed)
180
+ res.json(permissions);
181
+ }
182
+ catch (error) {
183
+ if (!controller.signal.aborted && !closed)
184
+ res
185
+ .status(500)
186
+ .json({ error: error instanceof Error ? error.message : "Could not request system permissions." });
187
+ }
188
+ finally {
189
+ res.off("close", abort);
190
+ permissionControllers.delete(controller);
191
+ }
192
+ });
193
+ app.post("/api/device-desktop/local/enable", localGuard, setupGuard, express.json({ limit: 256 }), (req, res) => {
194
+ if (!req.body || typeof req.body.enabled !== "boolean" || Object.keys(req.body).length !== 1) {
195
+ res.status(400).json({ error: "Expected only enabled boolean" });
196
+ return;
197
+ }
198
+ try {
199
+ setup.setEnabled(req.body.enabled);
200
+ if (!setup.enabled)
201
+ for (const cleanup of bridges)
202
+ cleanup();
203
+ res.json(status());
204
+ }
205
+ catch {
206
+ res.status(500).json({ error: "Could not save desktop settings" });
207
+ }
208
+ });
209
+ app.post("/api/device-desktop/setup/install", setupGuard, (_req, res) => res.json({ installation }));
210
+ app.post("/api/device-desktop/setup/enable", setupGuard, express.json({ limit: 256 }), (req, res) => {
211
+ if (!req.body || typeof req.body.enabled !== "boolean" || Object.keys(req.body).length !== 1) {
212
+ res.status(400).json({ error: "Expected only enabled boolean" });
213
+ return;
214
+ }
215
+ try {
216
+ setup.setEnabled(req.body.enabled);
217
+ if (!setup.enabled)
218
+ for (const cleanup of bridges)
219
+ cleanup();
220
+ res.json(status());
221
+ }
222
+ catch {
223
+ res.status(500).json({ error: "Could not save desktop settings" });
224
+ }
225
+ });
226
+ function bridge(ws, readOnly) {
227
+ let ended = false;
228
+ let capture;
229
+ let alive = true;
230
+ let lastActivity = Date.now();
231
+ let queued = 0;
232
+ let sending = false;
233
+ let awaitingAck = false;
234
+ let started = false;
235
+ let failing = false;
236
+ let closeTimer;
237
+ let captureClosed = false;
238
+ const stopCapture = () => {
239
+ if (!capture || captureClosed)
240
+ return;
241
+ captureClosed = true;
242
+ capture.close();
243
+ };
244
+ const cleanup = () => {
245
+ if (ended)
246
+ return;
247
+ ended = true;
248
+ clearTimeout(connectTimer);
249
+ clearInterval(heartbeat);
250
+ clearTimeout(closeTimer);
251
+ bridges.delete(cleanup);
252
+ stopCapture();
253
+ ws.terminate();
254
+ };
255
+ const fail = (message) => {
256
+ if (ended || failing)
257
+ return;
258
+ failing = true;
259
+ stopCapture();
260
+ if (ws.readyState === WebSocket.OPEN) {
261
+ ws.send(JSON.stringify({ type: "error", message: message.slice(0, 2048) }));
262
+ ws.close(1011, "Desktop capture failed");
263
+ closeTimer = setTimeout(cleanup, 2000);
264
+ closeTimer.unref();
265
+ }
266
+ else
267
+ cleanup();
268
+ };
269
+ const connectTimer = setTimeout(() => fail("Desktop capture timed out. Check screen capture permissions and the active graphical session."), DESKTOP_LIMITS.connectMs);
270
+ connectTimer.unref();
271
+ const heartbeat = setInterval(() => {
272
+ if (!alive || Date.now() - lastActivity > DESKTOP_LIMITS.idleMs)
273
+ return cleanup();
274
+ alive = false;
275
+ if (ws.readyState === WebSocket.OPEN)
276
+ ws.ping();
277
+ }, 30_000);
278
+ heartbeat.unref();
279
+ bridges.add(cleanup);
280
+ ws.on("pong", () => {
281
+ alive = true;
282
+ });
283
+ ws.on("close", cleanup);
284
+ ws.on("error", cleanup);
285
+ ws.on("message", (raw, binary) => {
286
+ if (ended)
287
+ return;
288
+ if (binary)
289
+ return cleanup();
290
+ let input;
291
+ try {
292
+ const value = JSON.parse(raw.toString());
293
+ if (value?.type === "ack" && Object.keys(value).length === 1) {
294
+ awaitingAck = false;
295
+ return;
296
+ }
297
+ input = parseDesktopInput(value);
298
+ }
299
+ catch {
300
+ /* Invalid input closes this connection. */
301
+ }
302
+ if (!input)
303
+ return cleanup();
304
+ lastActivity = Date.now();
305
+ if (!readOnly) {
306
+ try {
307
+ capture?.input(input);
308
+ }
309
+ catch {
310
+ fail("Could not send desktop input.");
311
+ }
312
+ }
313
+ });
314
+ try {
315
+ capture = backend.start({
316
+ readOnly,
317
+ onFrame: (jpeg) => {
318
+ if (ended || failing || ws.readyState !== WebSocket.OPEN)
319
+ return;
320
+ if (!jpeg.length || jpeg.length > DESKTOP_LIMITS.frame)
321
+ return fail("Desktop frame exceeds the capture size limit.");
322
+ if (!started) {
323
+ started = true;
324
+ clearTimeout(connectTimer);
325
+ ws.send(JSON.stringify({ type: "ready" }));
326
+ }
327
+ // Slow clients drop frames rather than building latency or an unbounded queue.
328
+ if (sending ||
329
+ awaitingAck ||
330
+ queued + jpeg.length > DESKTOP_LIMITS.queue ||
331
+ ws.bufferedAmount + jpeg.length > DESKTOP_LIMITS.queue)
332
+ return;
333
+ sending = true;
334
+ awaitingAck = true;
335
+ queued += jpeg.length;
336
+ ws.send(jpeg, { binary: true }, (error) => {
337
+ sending = false;
338
+ queued -= jpeg.length;
339
+ if (error)
340
+ cleanup();
341
+ });
342
+ },
343
+ onError: fail,
344
+ onClose: () => fail("Desktop capture stopped. Check the active desktop session and system permissions."),
345
+ });
346
+ if (ended || failing)
347
+ stopCapture();
348
+ }
349
+ catch (error) {
350
+ fail(error instanceof Error ? error.message : "Could not start desktop capture.");
351
+ }
352
+ }
353
+ return {
354
+ handleUpgrade(req, socket, head) {
355
+ let url;
356
+ try {
357
+ url = new URL(req.url ?? "/", "http://local");
358
+ }
359
+ catch {
360
+ return false;
361
+ }
362
+ if (url.pathname !== "/desktop-ws")
363
+ return false;
364
+ const reject = (code, reason) => socket.end(`HTTP/1.1 ${code} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
365
+ if (!allowed(req))
366
+ reject(403, "Forbidden");
367
+ else if (!setup.enabled || !backend.status().supported)
368
+ reject(503, "Unavailable");
369
+ else if (bridges.size >= DESKTOP_LIMITS.connections)
370
+ reject(429, "Too Many Requests");
371
+ else
372
+ wss.handleUpgrade(req, socket, head, (ws) => bridge(ws, url.searchParams.get("viewOnly") !== "0"));
373
+ return true;
374
+ },
375
+ close() {
376
+ if (closed)
377
+ return;
378
+ closed = true;
379
+ setup.close();
380
+ for (const controller of permissionControllers)
381
+ controller.abort();
382
+ for (const cleanup of bridges)
383
+ cleanup();
384
+ wss.close();
385
+ },
386
+ };
387
+ }
@@ -0,0 +1,241 @@
1
+ import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ const RESERVED = new Set([
5
+ "api",
6
+ "ws",
7
+ "device-connect",
8
+ "assets",
9
+ "auth",
10
+ "login",
11
+ "logout",
12
+ "register",
13
+ "devices",
14
+ "rooms",
15
+ "desktop",
16
+ "health",
17
+ "favicon",
18
+ "robots",
19
+ "static",
20
+ "open",
21
+ "portal",
22
+ "portals",
23
+ "device",
24
+ "device-open",
25
+ ]);
26
+ function fail(status, message) {
27
+ throw Object.assign(new Error(message), { status });
28
+ }
29
+ function validPort(value) {
30
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
31
+ }
32
+ function validAlias(value) {
33
+ return typeof value === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(value) && !RESERVED.has(value);
34
+ }
35
+ function validId(value) {
36
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 256 && !/[\x00-\x1f\x7f]/.test(value);
37
+ }
38
+ /** Comma-separated decimal ports; empty configuration disables portal allocation. */
39
+ export function parsePortalPorts(value) {
40
+ if (value === undefined || value.trim() === "")
41
+ return [];
42
+ const parts = value.split(",").map((part) => part.trim());
43
+ if (parts.some((part) => !/^[1-9][0-9]{0,4}$/.test(part)))
44
+ fail(400, "Invalid portal ports");
45
+ const ports = parts.map(Number);
46
+ if (ports.some((port) => !validPort(port)) || new Set(ports).size !== ports.length)
47
+ fail(400, "Invalid portal ports");
48
+ return ports;
49
+ }
50
+ /** Single-process registry. Allocations are published only after atomic replacement succeeds. */
51
+ export class DevicePortals {
52
+ path;
53
+ state;
54
+ pathAccess;
55
+ queue = Promise.resolve();
56
+ constructor(path, state, pathAccess) {
57
+ this.path = path;
58
+ this.state = state;
59
+ this.pathAccess = pathAccess;
60
+ }
61
+ static async open(dataDir, publicUrl, ports, options = {}) {
62
+ let url;
63
+ try {
64
+ url = new URL(publicUrl);
65
+ }
66
+ catch {
67
+ return fail(400, "Invalid portal public origin");
68
+ }
69
+ if (!["http:", "https:"].includes(url.protocol) ||
70
+ url.username ||
71
+ Reflect.get(url, "pass" + "word") ||
72
+ url.pathname !== "/" ||
73
+ url.search ||
74
+ url.hash)
75
+ fail(400, "Invalid portal public origin");
76
+ publicUrl = url.origin;
77
+ if (!Array.isArray(ports) || ports.some((port) => !validPort(port)) || new Set(ports).size !== ports.length)
78
+ fail(400, "Invalid portal ports");
79
+ const pool = [...ports].sort((a, b) => a - b);
80
+ const hubPort = Number(url.port || (url.protocol === "https:" ? 443 : 80));
81
+ if (pool.includes(hubPort))
82
+ fail(400, "Portal port overlaps hub origin");
83
+ await mkdir(dataDir, { recursive: true });
84
+ const path = join(dataDir, "device-portals.json");
85
+ let raw;
86
+ try {
87
+ raw = await readFile(path, "utf8");
88
+ }
89
+ catch (error) {
90
+ if (error.code !== "ENOENT")
91
+ throw error;
92
+ const registry = new DevicePortals(path, { version: 1, publicUrl, ports: pool, allocations: [] }, options.pathAccess === true);
93
+ await registry.persist(registry.state);
94
+ return registry;
95
+ }
96
+ let state;
97
+ try {
98
+ state = JSON.parse(raw);
99
+ if (!state ||
100
+ state.version !== 1 ||
101
+ state.publicUrl !== publicUrl ||
102
+ !Array.isArray(state.ports) ||
103
+ JSON.stringify(state.ports) !== JSON.stringify(pool) ||
104
+ !Array.isArray(state.allocations))
105
+ throw new Error("Invalid registry");
106
+ const devices = new Set();
107
+ const usedPorts = new Set();
108
+ const aliases = new Set();
109
+ for (const entry of state.allocations) {
110
+ if (!entry ||
111
+ !validId(entry.deviceId) ||
112
+ !validId(entry.accountId) ||
113
+ (entry.pathAccess !== undefined && typeof entry.pathAccess !== "boolean") ||
114
+ (entry.port === undefined
115
+ ? entry.pathAccess !== true
116
+ : !validPort(entry.port) || !pool.includes(entry.port) || usedPorts.has(entry.port)) ||
117
+ typeof entry.retired !== "boolean" ||
118
+ devices.has(entry.deviceId) ||
119
+ (entry.alias !== undefined && (!validAlias(entry.alias) || entry.retired || aliases.has(entry.alias))))
120
+ throw new Error("Invalid allocation");
121
+ devices.add(entry.deviceId);
122
+ if (entry.port !== undefined)
123
+ usedPorts.add(entry.port);
124
+ if (entry.alias !== undefined)
125
+ aliases.add(entry.alias);
126
+ }
127
+ }
128
+ catch {
129
+ throw new Error("Portal registry is malformed or configuration does not match");
130
+ }
131
+ return new DevicePortals(path, state, options.pathAccess === true);
132
+ }
133
+ getOrigin(deviceId) {
134
+ const entry = this.state.allocations.find((item) => item.deviceId === deviceId && !item.retired);
135
+ if (!entry)
136
+ return undefined;
137
+ if (this.pathAccess)
138
+ return `${this.state.publicUrl}/device/${encodeURIComponent(deviceId)}/`;
139
+ if (entry.port === undefined)
140
+ return undefined;
141
+ const url = new URL(this.state.publicUrl);
142
+ url.port = String(entry.port);
143
+ return url.origin;
144
+ }
145
+ getAlias(deviceId) {
146
+ return this.state.allocations.find((item) => item.deviceId === deviceId && !item.retired)?.alias;
147
+ }
148
+ resolveAlias(alias) {
149
+ const entry = this.state.allocations.find((item) => !item.retired && item.alias === alias);
150
+ return entry ? { deviceId: entry.deviceId, accountId: entry.accountId } : undefined;
151
+ }
152
+ /** Detached legacy origins only; path access must not enter the relay origin map. */
153
+ origins() {
154
+ const origins = new Map();
155
+ if (this.pathAccess)
156
+ return origins;
157
+ for (const entry of this.state.allocations) {
158
+ const origin = this.getOrigin(entry.deviceId);
159
+ if (origin)
160
+ origins.set(entry.deviceId, origin);
161
+ }
162
+ return origins;
163
+ }
164
+ async assign(deviceId, accountId, alias) {
165
+ return this.serialize(async () => {
166
+ if (!validId(deviceId) || !validId(accountId) || (alias !== undefined && !validAlias(alias)))
167
+ fail(400, "Invalid portal assignment");
168
+ const draft = structuredClone(this.state);
169
+ let entry = draft.allocations.find((item) => item.deviceId === deviceId);
170
+ if (entry && entry.accountId !== accountId)
171
+ fail(409, "Portal unavailable");
172
+ if (alias !== undefined && draft.allocations.some((item) => item.deviceId !== deviceId && item.alias === alias))
173
+ fail(409, "Portal unavailable");
174
+ if (!entry) {
175
+ entry = { deviceId, accountId, retired: false };
176
+ draft.allocations.push(entry);
177
+ }
178
+ if (this.pathAccess) {
179
+ if (entry.port === undefined)
180
+ entry.pathAccess = true;
181
+ }
182
+ else if (entry.port === undefined) {
183
+ const port = draft.ports.find((port) => !draft.allocations.some((item) => item.port === port));
184
+ if (port === undefined)
185
+ fail(409, "Portal unavailable");
186
+ entry.port = port;
187
+ delete entry.pathAccess;
188
+ }
189
+ entry.retired = false;
190
+ if (alias !== undefined)
191
+ entry.alias = alias;
192
+ await this.persist(draft);
193
+ this.state = draft;
194
+ return {
195
+ deviceId: entry.deviceId,
196
+ accountId: entry.accountId,
197
+ ...(entry.port === undefined ? {} : { port: entry.port }),
198
+ ...(entry.alias === undefined ? {} : { alias: entry.alias }),
199
+ };
200
+ });
201
+ }
202
+ async retire(deviceId) {
203
+ await this.serialize(async () => {
204
+ if (!validId(deviceId))
205
+ fail(400, "Invalid deviceId");
206
+ const draft = structuredClone(this.state);
207
+ const entry = draft.allocations.find((item) => item.deviceId === deviceId);
208
+ if (!entry || entry.retired)
209
+ return;
210
+ entry.retired = true;
211
+ delete entry.alias;
212
+ await this.persist(draft);
213
+ this.state = draft;
214
+ });
215
+ }
216
+ serialize(operation) {
217
+ const result = this.queue.then(operation);
218
+ this.queue = result.catch(() => { });
219
+ return result;
220
+ }
221
+ async persist(state) {
222
+ const temporary = `${this.path}.${randomUUID()}.tmp`;
223
+ try {
224
+ const file = await open(temporary, "wx", 0o600);
225
+ try {
226
+ await file.writeFile(JSON.stringify(state));
227
+ await file.sync();
228
+ }
229
+ finally {
230
+ await file.close();
231
+ }
232
+ await rename(temporary, this.path);
233
+ }
234
+ finally {
235
+ await unlink(temporary).catch((error) => {
236
+ if (error.code !== "ENOENT")
237
+ throw error;
238
+ });
239
+ }
240
+ }
241
+ }