pi-web-ui 0.113.1 → 0.114.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. 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
+ }