pi-web-ui 0.113.1 → 0.114.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +71 -1
- package/README.md +187 -316
- package/README.zh-CN.md +227 -299
- package/README.zh-TW.md +227 -299
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/frp-manager.mjs +1573 -1573
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +4081 -4041
- package/deploy/nginx-subpath.conf +100 -100
- package/deploy/pi-web-ui.service +36 -36
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2419 -1174
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +69 -13
- package/dist/server/canvas/canvas-agent-tool.js +68 -18
- package/dist/server/canvas/canvas-cards.js +1 -1
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +519 -202
- package/dist/server/canvas/canvas-scheduled-task.js +45 -0
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +110 -24
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +351 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +830 -0
- package/dist/server/device-center/local-hub.js +92 -0
- package/dist/server/device-center/local.js +529 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +996 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +84 -27
- package/dist/server/dsh/dsh-agent-service.js +282 -159
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
- package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
- package/dist/server/dsh/runtime/launcher.mjs +235 -235
- package/dist/server/dsh/runtime/override.patch.yml +89 -89
- package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/engine-probe.js +36 -6
- package/dist/server/eval-tool.js +135 -135
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +38 -26
- package/dist/server/global-loader.js +40 -2
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +285 -255
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/patch-bash-process.js +125 -0
- package/dist/server/patch-tool.js +9 -9
- package/dist/server/patch-turn-end-boundary.js +3 -3
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/persona-chain.js +8 -8
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +288 -94
- package/dist/server/preset-fields.js +56 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +113 -72
- package/dist/server/prompt-templates.js +106 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +199 -106
- package/dist/server/request-context.js +164 -0
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/schedule-agent-tool.js +39 -21
- package/dist/server/scheduler-tasks.js +106 -55
- package/dist/server/scm-commitmsg.js +10 -10
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +273 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/setup-page.js +620 -620
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/text-quote.js +9 -0
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +48 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/drivers/claude-code.js +5 -0
- package/dist/server/universal/drivers/codex.js +336 -0
- package/dist/server/universal/index.js +1 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-attachments.js +24 -1
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +357 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/vision-bridge.js +18 -18
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/docs/device-center.md +148 -0
- package/docs/device-desktop.md +48 -0
- package/docs/dsh-engine.md +493 -493
- package/extensions/webui.ts +335 -335
- package/package.json +5 -2
- package/plugin-sdk/README.md +174 -174
- package/plugin-sdk/client-utils.mjs +279 -279
- package/plugin-sdk/import-check.mjs +210 -210
- package/plugin-sdk/index.d.ts +698 -676
- package/plugin-sdk/index.mjs +696 -696
- package/plugin-sdk/package.json +13 -13
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +11 -1
- package/themes/aetheris.css +501 -607
- package/themes/ayu-light.css +116 -140
- package/themes/bases/flow-base.css +1357 -1363
- package/themes/bases/obsidian-base.css +895 -895
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +688 -687
- package/themes/bases/zhupi-base.css +660 -659
- package/themes/catppuccin-latte.css +119 -142
- package/themes/catppuccin.css +116 -147
- package/themes/claude-code-dark.css +147 -146
- package/themes/codex.css +114 -138
- package/themes/cyberpunk.css +50 -108
- package/themes/dark-teal.css +264 -265
- package/themes/dazzle.css +38 -108
- package/themes/everforest-light.css +115 -138
- package/themes/flow-light.css +164 -164
- package/themes/flow.css +161 -161
- package/themes/geist.css +114 -138
- package/themes/gruvbox-light.css +115 -138
- package/themes/kanagawa-lotus.css +115 -138
- package/themes/md-preview.css +24 -234
- package/themes/mist.css +166 -186
- package/themes/nord.css +107 -138
- package/themes/one-dark.css +106 -139
- package/themes/paper.css +174 -186
- package/themes/rose-pine-dawn.css +114 -138
- package/themes/sakura.css +166 -186
- package/themes/solarized-light.css +114 -137
- package/themes/tokyo-night.css +115 -146
- package/themes/translucent.css +85 -85
- package/themes/transparent.css +116 -116
- package/themes/vs-code-dark.css +147 -147
- package/themes/wallpaper-flow.css +382 -382
- package/themes/wallpaper-obsidian.css +74 -74
- package/themes/white.css +164 -186
- package/themes/zhujian-dark.css +115 -114
- package/themes/zhujian.css +114 -114
- package/themes/zhupi-dark.css +115 -114
- package/themes/zhupi.css +114 -114
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
- package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
- package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
- package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
- package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
- package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
- package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
- package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
- package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
- package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
- package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
- package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
- package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
- package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
- package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
- package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
- package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
- package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
- package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
- package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
- package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
- package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
- package/web/dist/assets/desktop-YguLbrX1.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
- package/web/dist/assets/index-BPvpea8t.js +85 -0
- package/web/dist/assets/index-D6u8xH0o.js +85 -0
- package/web/dist/assets/index-DDZMv6LO.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +42 -35
- package/web/dist/sw.js +179 -179
- package/web/public/sw.js +179 -179
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
- package/web/dist/assets/index-ByiO9f-N.js +0 -2008
- package/web/dist/assets/index-ycGLh4a4.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -0,0 +1,996 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { WebSocket, WebSocketServer } from "ws";
|
|
3
|
+
import { capabilityBase, createPortalResponse, parseDevicePath, portalHeaders, wrapperHtml } from "./path-portal.js";
|
|
4
|
+
export const RELAY_LIMITS = {
|
|
5
|
+
frame: 128 * 1024,
|
|
6
|
+
chunk: 32 * 1024,
|
|
7
|
+
queue: 2 * 1024 * 1024,
|
|
8
|
+
body: 64 * 1024 * 1024,
|
|
9
|
+
streams: 32,
|
|
10
|
+
devices: 128,
|
|
11
|
+
sessions: 2048,
|
|
12
|
+
};
|
|
13
|
+
export function loopback(host) {
|
|
14
|
+
return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
|
|
15
|
+
}
|
|
16
|
+
export function checkedUrl(value) {
|
|
17
|
+
const url = new URL(value);
|
|
18
|
+
if (url.username ||
|
|
19
|
+
url[("pass" + "word")] ||
|
|
20
|
+
url.hash ||
|
|
21
|
+
!["https:", "wss:", "http:", "ws:"].includes(url.protocol))
|
|
22
|
+
throw new Error("HTTP(S) or WS(S) URL required, without credentials or fragment");
|
|
23
|
+
return url;
|
|
24
|
+
}
|
|
25
|
+
export function sendFrame(ws, frame) {
|
|
26
|
+
const data = JSON.stringify(frame);
|
|
27
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
28
|
+
return false;
|
|
29
|
+
if (Buffer.byteLength(data) > RELAY_LIMITS.frame ||
|
|
30
|
+
ws.bufferedAmount + Buffer.byteLength(data) > RELAY_LIMITS.queue) {
|
|
31
|
+
ws.terminate();
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
ws.send(data, (error) => {
|
|
35
|
+
if (error)
|
|
36
|
+
ws.terminate();
|
|
37
|
+
});
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
export function parseFrame(data) {
|
|
41
|
+
if (data.length > RELAY_LIMITS.frame)
|
|
42
|
+
throw new Error("Frame too large");
|
|
43
|
+
const frame = JSON.parse(data.toString());
|
|
44
|
+
if (!frame || typeof frame !== "object" || typeof frame.type !== "string")
|
|
45
|
+
throw new Error("Invalid frame");
|
|
46
|
+
return frame;
|
|
47
|
+
}
|
|
48
|
+
export function decodeChunk(value) {
|
|
49
|
+
if (typeof value !== "string" ||
|
|
50
|
+
value.length > Math.ceil(RELAY_LIMITS.chunk / 3) * 4 ||
|
|
51
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))
|
|
52
|
+
throw new Error("Invalid chunk");
|
|
53
|
+
return Buffer.from(value, "base64");
|
|
54
|
+
}
|
|
55
|
+
export function sendChunks(ws, type, id, data, extra = {}) {
|
|
56
|
+
for (let offset = 0; offset < data.length; offset += RELAY_LIMITS.chunk)
|
|
57
|
+
if (!sendFrame(ws, {
|
|
58
|
+
type,
|
|
59
|
+
id,
|
|
60
|
+
data: data.subarray(offset, offset + RELAY_LIMITS.chunk).toString("base64"),
|
|
61
|
+
...extra,
|
|
62
|
+
}))
|
|
63
|
+
return false;
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
const blocked = /^(host|cookie|authorization|proxy-.*|origin|referer|forwarded|x-forwarded-.*|connection|upgrade|keep-alive|transfer-encoding|te|trailer|sec-websocket-.*|set-cookie)$/i;
|
|
67
|
+
export function cleanHeaders(headers) {
|
|
68
|
+
const result = {};
|
|
69
|
+
const connection = String(headers.connection || "")
|
|
70
|
+
.toLowerCase()
|
|
71
|
+
.split(",")
|
|
72
|
+
.map((x) => x.trim());
|
|
73
|
+
for (const [key, value] of Object.entries(headers))
|
|
74
|
+
if (!blocked.test(key) &&
|
|
75
|
+
!connection.includes(key.toLowerCase()) &&
|
|
76
|
+
typeof value === "string" &&
|
|
77
|
+
!/[\r\n]/.test(value))
|
|
78
|
+
result[key.toLowerCase()] = value;
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
export function safePath(path, method = "GET") {
|
|
82
|
+
if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//") || /[\r\n\\]/.test(path))
|
|
83
|
+
return false;
|
|
84
|
+
try {
|
|
85
|
+
let decoded = path.split("?")[0];
|
|
86
|
+
for (let i = 0; i < 8; i++) {
|
|
87
|
+
const next = decodeURIComponent(decoded);
|
|
88
|
+
if (next === decoded)
|
|
89
|
+
break;
|
|
90
|
+
decoded = next;
|
|
91
|
+
}
|
|
92
|
+
if (/%|[\\\x00-\x20]/.test(decoded))
|
|
93
|
+
return false;
|
|
94
|
+
const normalized = new URL(decoded, "http://local").pathname.toLowerCase();
|
|
95
|
+
// OS authorization is initiated only on the device itself, never through a Hub portal.
|
|
96
|
+
if (normalized === "/api/device-desktop/local" || normalized.startsWith("/api/device-desktop/local/"))
|
|
97
|
+
return false;
|
|
98
|
+
if (normalized === "/api/device-center" || normalized.startsWith("/api/device-center/")) {
|
|
99
|
+
// Only account-scoped chat routes may cross a device portal.
|
|
100
|
+
if (method === "GET") {
|
|
101
|
+
return /^\/api\/device-center\/(chat-status|devices|bots|rooms(?:\/[^/]+)?)$/.test(normalized);
|
|
102
|
+
}
|
|
103
|
+
if (method === "POST")
|
|
104
|
+
return /^\/api\/device-center\/rooms(?:\/[^/]+\/(messages|rename|members|delete))?$/.test(normalized);
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
return !["/devices", "/setup", "/api/setup"].some((prefix) => normalized === prefix || normalized.startsWith(prefix + "/"));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
export const COMMANDS = ["transfer_stage", "transfer_preview", "transfer_apply"];
|
|
114
|
+
const RPC_BYTES = 12 * 1024 * 1024;
|
|
115
|
+
/** Bounded chunked RPC, scoped to exactly one authenticated connection. */
|
|
116
|
+
export function createCommandChannel(ws, handler) {
|
|
117
|
+
const pending = new Map();
|
|
118
|
+
let ended = false;
|
|
119
|
+
function remove(id, error) {
|
|
120
|
+
const item = pending.get(id);
|
|
121
|
+
if (!item)
|
|
122
|
+
return;
|
|
123
|
+
pending.delete(id);
|
|
124
|
+
clearTimeout(item.timer);
|
|
125
|
+
item.detach?.();
|
|
126
|
+
item.controller.abort();
|
|
127
|
+
if (error)
|
|
128
|
+
item.reject?.(error);
|
|
129
|
+
}
|
|
130
|
+
function add(id, incoming) {
|
|
131
|
+
if (ended || pending.size >= 4 || pending.has(id))
|
|
132
|
+
throw new Error("Command capacity exceeded");
|
|
133
|
+
const timer = setTimeout(() => {
|
|
134
|
+
sendFrame(ws, { type: "rpc_cancel", id });
|
|
135
|
+
remove(id, new Error("Command timed out"));
|
|
136
|
+
}, 60_000);
|
|
137
|
+
timer.unref();
|
|
138
|
+
const item = {
|
|
139
|
+
chunks: [],
|
|
140
|
+
bytes: 0,
|
|
141
|
+
incoming,
|
|
142
|
+
controller: new AbortController(),
|
|
143
|
+
timer,
|
|
144
|
+
};
|
|
145
|
+
pending.set(id, item);
|
|
146
|
+
return item;
|
|
147
|
+
}
|
|
148
|
+
async function transmit(id, type, value, signal) {
|
|
149
|
+
const json = JSON.stringify(value ?? null);
|
|
150
|
+
if (json.length > RPC_BYTES)
|
|
151
|
+
throw new Error("Command payload too large");
|
|
152
|
+
const bytes = Buffer.from(json);
|
|
153
|
+
if (bytes.length > RPC_BYTES)
|
|
154
|
+
throw new Error("Command payload too large");
|
|
155
|
+
for (let offset = 0; offset < bytes.length; offset += RELAY_LIMITS.chunk) {
|
|
156
|
+
while (ws.bufferedAmount > RELAY_LIMITS.queue / 2) {
|
|
157
|
+
await new Promise((resolve) => {
|
|
158
|
+
const timer = setTimeout(resolve, 5);
|
|
159
|
+
timer.unref();
|
|
160
|
+
});
|
|
161
|
+
if (signal.aborted || ended || ws.readyState !== WebSocket.OPEN)
|
|
162
|
+
throw new Error("Command cancelled");
|
|
163
|
+
}
|
|
164
|
+
if (signal.aborted ||
|
|
165
|
+
ended ||
|
|
166
|
+
!sendFrame(ws, {
|
|
167
|
+
type: `${type}_chunk`,
|
|
168
|
+
id,
|
|
169
|
+
data: bytes.subarray(offset, offset + RELAY_LIMITS.chunk).toString("base64"),
|
|
170
|
+
}))
|
|
171
|
+
throw new Error("Command cancelled");
|
|
172
|
+
}
|
|
173
|
+
if (!sendFrame(ws, { type: `${type}_end`, id }))
|
|
174
|
+
throw new Error("Command disconnected");
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
call(action, payload, options = {}) {
|
|
178
|
+
if (!COMMANDS.includes(action))
|
|
179
|
+
return Promise.reject(new Error("Command forbidden"));
|
|
180
|
+
if (options.signal?.aborted)
|
|
181
|
+
return Promise.reject(new Error("Command cancelled"));
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
const id = randomUUID();
|
|
184
|
+
let item;
|
|
185
|
+
try {
|
|
186
|
+
item = add(id, false);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
reject(error);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
item.resolve = resolve;
|
|
193
|
+
item.reject = reject;
|
|
194
|
+
const abort = () => {
|
|
195
|
+
sendFrame(ws, { type: "rpc_cancel", id });
|
|
196
|
+
remove(id, new Error("Command cancelled"));
|
|
197
|
+
};
|
|
198
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
199
|
+
item.detach = () => options.signal?.removeEventListener("abort", abort);
|
|
200
|
+
if (!sendFrame(ws, { type: "rpc_start", id, action })) {
|
|
201
|
+
remove(id, new Error("Command disconnected"));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
void transmit(id, "rpc_request", payload, item.controller.signal).catch((error) => {
|
|
205
|
+
sendFrame(ws, { type: "rpc_cancel", id });
|
|
206
|
+
remove(id, error);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
},
|
|
210
|
+
handle(frame) {
|
|
211
|
+
if (!frame.type.startsWith("rpc_"))
|
|
212
|
+
return false;
|
|
213
|
+
const id = frame.id;
|
|
214
|
+
if (typeof id !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(id))
|
|
215
|
+
throw new Error("Invalid command id");
|
|
216
|
+
if (frame.type === "rpc_start") {
|
|
217
|
+
if (!handler || !COMMANDS.includes(frame.action)) {
|
|
218
|
+
sendFrame(ws, { type: "rpc_error", id });
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
const item = add(id, true);
|
|
222
|
+
item.action = frame.action;
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
const item = pending.get(id);
|
|
226
|
+
if (!item)
|
|
227
|
+
return true;
|
|
228
|
+
if (frame.type === "rpc_cancel" || frame.type === "rpc_error") {
|
|
229
|
+
remove(id, new Error("Remote command rejected"));
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
if (item.executing)
|
|
233
|
+
throw new Error("Command already executing");
|
|
234
|
+
const prefix = item.incoming ? "rpc_request" : "rpc_response";
|
|
235
|
+
if (frame.type === `${prefix}_chunk`) {
|
|
236
|
+
const data = decodeChunk(frame.data);
|
|
237
|
+
item.bytes += data.length;
|
|
238
|
+
if (!data.length || item.bytes > RPC_BYTES || item.chunks.length >= Math.ceil(RPC_BYTES / RELAY_LIMITS.chunk))
|
|
239
|
+
throw new Error("Command too large");
|
|
240
|
+
item.chunks.push(data);
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
if (frame.type !== `${prefix}_end`)
|
|
244
|
+
throw new Error("Invalid command frame");
|
|
245
|
+
const value = JSON.parse(Buffer.concat(item.chunks, item.bytes).toString("utf8"));
|
|
246
|
+
item.chunks = [];
|
|
247
|
+
item.bytes = 0;
|
|
248
|
+
if (!item.incoming) {
|
|
249
|
+
item.resolve?.(value);
|
|
250
|
+
remove(id);
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
item.executing = true;
|
|
254
|
+
const run = async () => {
|
|
255
|
+
try {
|
|
256
|
+
const result = await handler(item.action, value, item.controller.signal);
|
|
257
|
+
if (pending.get(id) !== item)
|
|
258
|
+
return;
|
|
259
|
+
await transmit(id, "rpc_response", result, item.controller.signal);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
if (pending.get(id) === item)
|
|
263
|
+
sendFrame(ws, { type: "rpc_error", id });
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
remove(id);
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
void run();
|
|
270
|
+
return true;
|
|
271
|
+
},
|
|
272
|
+
close() {
|
|
273
|
+
ended = true;
|
|
274
|
+
for (const id of pending.keys())
|
|
275
|
+
remove(id, new Error("Device disconnected"));
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
export const WS_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
280
|
+
/** Connection-scoped, bounded message assembly and outbound queue. */
|
|
281
|
+
export function createWsMessageChannel(transport) {
|
|
282
|
+
const assemblies = new Map();
|
|
283
|
+
let aggregate = 0;
|
|
284
|
+
let queued = 0;
|
|
285
|
+
let queuedMessages = 0;
|
|
286
|
+
let ended = false;
|
|
287
|
+
let tail = Promise.resolve();
|
|
288
|
+
function discard(id) {
|
|
289
|
+
const item = assemblies.get(id);
|
|
290
|
+
if (item) {
|
|
291
|
+
clearTimeout(item.timer);
|
|
292
|
+
aggregate -= item.bytes;
|
|
293
|
+
assemblies.delete(id);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
send(id, data, binary) {
|
|
298
|
+
if (ended ||
|
|
299
|
+
queuedMessages >= 128 ||
|
|
300
|
+
data.length > WS_MESSAGE_BYTES ||
|
|
301
|
+
queued + data.length > 2 * WS_MESSAGE_BYTES)
|
|
302
|
+
return false;
|
|
303
|
+
queuedMessages++;
|
|
304
|
+
queued += Math.max(1, data.length);
|
|
305
|
+
tail = tail
|
|
306
|
+
.then(async () => {
|
|
307
|
+
const messageId = randomUUID();
|
|
308
|
+
for (let offset = 0; offset < data.length; offset += RELAY_LIMITS.chunk) {
|
|
309
|
+
while (transport.bufferedAmount > RELAY_LIMITS.queue / 2) {
|
|
310
|
+
await new Promise((resolve) => {
|
|
311
|
+
const timer = setTimeout(resolve, 5);
|
|
312
|
+
timer.unref();
|
|
313
|
+
});
|
|
314
|
+
if (ended || transport.readyState !== WebSocket.OPEN)
|
|
315
|
+
throw new Error("Disconnected");
|
|
316
|
+
}
|
|
317
|
+
if (ended ||
|
|
318
|
+
!sendFrame(transport, {
|
|
319
|
+
type: "ws_chunk",
|
|
320
|
+
id,
|
|
321
|
+
messageId,
|
|
322
|
+
binary,
|
|
323
|
+
data: data.subarray(offset, offset + RELAY_LIMITS.chunk).toString("base64"),
|
|
324
|
+
}))
|
|
325
|
+
throw new Error("Disconnected");
|
|
326
|
+
}
|
|
327
|
+
if (ended || !sendFrame(transport, { type: "ws_end", id, messageId, binary }))
|
|
328
|
+
throw new Error("Disconnected");
|
|
329
|
+
})
|
|
330
|
+
.catch(() => transport.terminate())
|
|
331
|
+
.finally(() => {
|
|
332
|
+
queued -= Math.max(1, data.length);
|
|
333
|
+
queuedMessages--;
|
|
334
|
+
});
|
|
335
|
+
return true;
|
|
336
|
+
},
|
|
337
|
+
receive(frame, target) {
|
|
338
|
+
const id = frame.id;
|
|
339
|
+
if (typeof frame.messageId !== "string" || frame.messageId.length > 64 || typeof frame.binary !== "boolean")
|
|
340
|
+
throw new Error("Invalid WS message");
|
|
341
|
+
let item = assemblies.get(id);
|
|
342
|
+
if (!item) {
|
|
343
|
+
if (assemblies.size >= RELAY_LIMITS.streams)
|
|
344
|
+
throw new Error("Too many WS messages");
|
|
345
|
+
const timer = setTimeout(() => {
|
|
346
|
+
discard(id);
|
|
347
|
+
target.terminate();
|
|
348
|
+
}, 60_000);
|
|
349
|
+
timer.unref();
|
|
350
|
+
item = { messageId: frame.messageId, binary: frame.binary, chunks: [], bytes: 0, timer };
|
|
351
|
+
assemblies.set(id, item);
|
|
352
|
+
}
|
|
353
|
+
if (item.messageId !== frame.messageId || item.binary !== frame.binary)
|
|
354
|
+
throw new Error("Interleaved WS message");
|
|
355
|
+
if (frame.type === "ws_chunk") {
|
|
356
|
+
const data = decodeChunk(frame.data);
|
|
357
|
+
if (!data.length ||
|
|
358
|
+
item.bytes + data.length > WS_MESSAGE_BYTES ||
|
|
359
|
+
aggregate + data.length > 2 * WS_MESSAGE_BYTES ||
|
|
360
|
+
item.chunks.length >= WS_MESSAGE_BYTES / RELAY_LIMITS.chunk)
|
|
361
|
+
throw new Error("WS assembly exceeded");
|
|
362
|
+
item.chunks.push(data);
|
|
363
|
+
item.bytes += data.length;
|
|
364
|
+
aggregate += data.length;
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (frame.type !== "ws_end")
|
|
368
|
+
throw new Error("Invalid WS frame");
|
|
369
|
+
const data = Buffer.concat(item.chunks, item.bytes);
|
|
370
|
+
discard(id);
|
|
371
|
+
if (target.readyState !== WebSocket.OPEN || target.bufferedAmount + data.length > 2 * WS_MESSAGE_BYTES)
|
|
372
|
+
throw new Error("WS target queue exceeded");
|
|
373
|
+
target.send(data, { binary: item.binary }, (error) => {
|
|
374
|
+
if (error)
|
|
375
|
+
target.terminate();
|
|
376
|
+
});
|
|
377
|
+
},
|
|
378
|
+
discard,
|
|
379
|
+
close() {
|
|
380
|
+
ended = true;
|
|
381
|
+
for (const id of assemblies.keys())
|
|
382
|
+
discard(id);
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
export function createDeviceRelay(options) {
|
|
387
|
+
const hub = checkedUrl(options.publicUrl);
|
|
388
|
+
const domain = options.deviceDomain?.toLowerCase();
|
|
389
|
+
if (domain !== undefined) {
|
|
390
|
+
if (!/^[a-z0-9.-]+(?::\d+)?$/.test(domain))
|
|
391
|
+
throw new Error("Invalid device domain");
|
|
392
|
+
const parsed = new URL(`${hub.protocol}//${domain}`);
|
|
393
|
+
if (parsed.host !== domain)
|
|
394
|
+
throw new Error("Invalid device domain");
|
|
395
|
+
const domainHost = parsed.hostname;
|
|
396
|
+
if (hub.hostname === domainHost ||
|
|
397
|
+
hub.hostname.endsWith(`.${domainHost}`) ||
|
|
398
|
+
domainHost.endsWith(`.${hub.hostname}`))
|
|
399
|
+
throw new Error("Device domain must be independent of hub domain");
|
|
400
|
+
}
|
|
401
|
+
if (!["http:", "https:"].includes(hub.protocol) || hub.pathname !== "/" || hub.search)
|
|
402
|
+
throw new Error("publicUrl must be an HTTP(S) root origin");
|
|
403
|
+
const devices = new Map();
|
|
404
|
+
// Slow browser responses apply transport backpressure instead of losing resource bodies.
|
|
405
|
+
const stalledResponses = new WeakMap();
|
|
406
|
+
function pauseForResponse(ws, res) {
|
|
407
|
+
let stalled = stalledResponses.get(ws);
|
|
408
|
+
if (!stalled)
|
|
409
|
+
stalledResponses.set(ws, (stalled = new Set()));
|
|
410
|
+
if (stalled.has(res))
|
|
411
|
+
return;
|
|
412
|
+
stalled.add(res);
|
|
413
|
+
ws.pause();
|
|
414
|
+
const resume = () => {
|
|
415
|
+
res.off("drain", resume);
|
|
416
|
+
res.off("close", resume);
|
|
417
|
+
stalled.delete(res);
|
|
418
|
+
if (!stalled.size && ws.readyState === WebSocket.OPEN)
|
|
419
|
+
ws.resume();
|
|
420
|
+
};
|
|
421
|
+
res.once("drain", resume);
|
|
422
|
+
res.once("close", resume);
|
|
423
|
+
}
|
|
424
|
+
const tickets = new Map();
|
|
425
|
+
const sessions = new Map();
|
|
426
|
+
const capabilities = new Map();
|
|
427
|
+
const pathRequest = (req) => options.pathAccess && req.headers.host?.toLowerCase() === hub.host.toLowerCase() ? parseDevicePath(req.url) : null;
|
|
428
|
+
function pathAuthorized(req, id, websocket = false) {
|
|
429
|
+
const path = pathRequest(req);
|
|
430
|
+
const session = path?.token ? capabilities.get(path.token) : undefined;
|
|
431
|
+
return !!(session &&
|
|
432
|
+
session.deviceId === id &&
|
|
433
|
+
session.expiresAt > Date.now() &&
|
|
434
|
+
path?.path &&
|
|
435
|
+
(!websocket || safePath(path.path, "WS")) &&
|
|
436
|
+
(!req.headers.origin || req.headers.origin === "null") &&
|
|
437
|
+
(!websocket || req.headers.origin === "null"));
|
|
438
|
+
}
|
|
439
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: RELAY_LIMITS.frame, perMessageDeflate: false });
|
|
440
|
+
const browserWss = new WebSocketServer({ noServer: true, maxPayload: WS_MESSAGE_BYTES, perMessageDeflate: false });
|
|
441
|
+
let closed = false;
|
|
442
|
+
let revision = 0;
|
|
443
|
+
let authenticating = 0;
|
|
444
|
+
const alive = new WeakSet();
|
|
445
|
+
const origin = (id) => options.deviceOrigins?.().get(id) ?? (domain ? `${hub.protocol}//${id}.${domain}` : undefined);
|
|
446
|
+
const deviceCookie = (id) => `${hub.protocol === "https:" ? "__Host-device" : "device"}${options.deviceOrigins?.().has(id) ? `-${new URL(origin(id)).port}-${id}` : ""}`;
|
|
447
|
+
const deviceId = (req) => {
|
|
448
|
+
const path = pathRequest(req);
|
|
449
|
+
if (path)
|
|
450
|
+
return path.id;
|
|
451
|
+
for (const [id, value] of options.deviceOrigins?.() ?? []) {
|
|
452
|
+
if (req.headers.host?.toLowerCase() === new URL(value).host.toLowerCase())
|
|
453
|
+
return id;
|
|
454
|
+
}
|
|
455
|
+
if (!domain)
|
|
456
|
+
return null;
|
|
457
|
+
const host = req.headers.host?.toLowerCase() || "";
|
|
458
|
+
const suffix = `.${domain}`;
|
|
459
|
+
if (!host.endsWith(suffix))
|
|
460
|
+
return null;
|
|
461
|
+
const id = host.slice(0, -suffix.length);
|
|
462
|
+
return /^[a-z0-9][a-z0-9-]{0,62}$/.test(id) ? id : null;
|
|
463
|
+
};
|
|
464
|
+
function authorized(req, id, websocket = false) {
|
|
465
|
+
const cookieName = deviceCookie(id);
|
|
466
|
+
const cookie = req.headers.cookie
|
|
467
|
+
?.split(";")
|
|
468
|
+
.map((x) => x.trim())
|
|
469
|
+
.find((x) => x.startsWith(`${cookieName}=`))
|
|
470
|
+
?.slice(cookieName.length + 1);
|
|
471
|
+
const session = cookie ? sessions.get(cookie) : undefined;
|
|
472
|
+
if (!session || session.deviceId !== id || session.expiresAt <= Date.now())
|
|
473
|
+
return false;
|
|
474
|
+
if (req.headers.origin && req.headers.origin !== origin(id))
|
|
475
|
+
return false;
|
|
476
|
+
if (websocket && req.headers.origin !== origin(id))
|
|
477
|
+
return false;
|
|
478
|
+
if (!["GET", "HEAD", "OPTIONS"].includes(req.method || "GET") && req.headers.origin !== origin(id))
|
|
479
|
+
return false;
|
|
480
|
+
return true;
|
|
481
|
+
}
|
|
482
|
+
function drop(id, entry) {
|
|
483
|
+
entry.rpc.close();
|
|
484
|
+
entry.messages.close();
|
|
485
|
+
for (const [taskId, { attemptId, botId }] of entry.tasks) {
|
|
486
|
+
Promise.resolve()
|
|
487
|
+
.then(() => options.onTaskEvent?.(id, {
|
|
488
|
+
taskId,
|
|
489
|
+
botId,
|
|
490
|
+
attemptId,
|
|
491
|
+
status: "interrupted",
|
|
492
|
+
report: "Device connection lost; task is not replayed",
|
|
493
|
+
}))
|
|
494
|
+
.catch(() => { });
|
|
495
|
+
}
|
|
496
|
+
entry.tasks.clear();
|
|
497
|
+
for (const stream of entry.streams.values()) {
|
|
498
|
+
clearTimeout(stream.timer);
|
|
499
|
+
stream.res?.destroy();
|
|
500
|
+
stream.ws?.terminate();
|
|
501
|
+
}
|
|
502
|
+
entry.streams.clear();
|
|
503
|
+
if (devices.get(id) === entry)
|
|
504
|
+
devices.delete(id);
|
|
505
|
+
}
|
|
506
|
+
function addStream(entry, id, stream) {
|
|
507
|
+
const timer = setTimeout(() => {
|
|
508
|
+
stream.res?.destroy();
|
|
509
|
+
stream.ws?.terminate();
|
|
510
|
+
entry.streams.delete(id);
|
|
511
|
+
sendFrame(entry.ws, { type: "cancel", id });
|
|
512
|
+
}, 30 * 60_000);
|
|
513
|
+
timer.unref();
|
|
514
|
+
const item = { ...stream, bytes: 0, timer };
|
|
515
|
+
entry.streams.set(id, item);
|
|
516
|
+
return item;
|
|
517
|
+
}
|
|
518
|
+
async function handleOpen(req, res, id, redirect = false) {
|
|
519
|
+
const generation = revision;
|
|
520
|
+
const account = await options.getAccount(req);
|
|
521
|
+
const accountId = typeof account === "string" ? account : account?.id;
|
|
522
|
+
if (closed ||
|
|
523
|
+
(redirect ? req.method !== "GET" : req.method !== "POST") ||
|
|
524
|
+
req.headers.host !== hub.host ||
|
|
525
|
+
(!redirect && req.headers.origin !== hub.origin) ||
|
|
526
|
+
!accountId ||
|
|
527
|
+
!(await options.ownsDevice(accountId, id))) {
|
|
528
|
+
res.writeHead(403).end();
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (!options.pathAccess && !origin(id)) {
|
|
532
|
+
res.writeHead(409, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({
|
|
533
|
+
error: "Device web access requires an independent origin",
|
|
534
|
+
code: "DEVICE_WEB_ORIGIN_REQUIRED",
|
|
535
|
+
}));
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (generation !== revision || closed || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(id) || !devices.has(id)) {
|
|
539
|
+
res.writeHead(409).end();
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (tickets.size >= RELAY_LIMITS.sessions) {
|
|
543
|
+
res.writeHead(503).end();
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
const ticket = randomBytes(32).toString("hex");
|
|
547
|
+
const expiresAt = Date.now() + 30_000;
|
|
548
|
+
tickets.set(ticket, { deviceId: id, accountId, generation, expiresAt });
|
|
549
|
+
const url = options.pathAccess
|
|
550
|
+
? `${hub.origin}/device/${id}/__open?ticket=${ticket}`
|
|
551
|
+
: `${origin(id)}/__device/open?ticket=${ticket}`;
|
|
552
|
+
if (redirect)
|
|
553
|
+
res.writeHead(302, { location: url, "cache-control": "no-store", "referrer-policy": "no-referrer" }).end();
|
|
554
|
+
else
|
|
555
|
+
res
|
|
556
|
+
.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" })
|
|
557
|
+
.end(JSON.stringify({ url, expiresAt }));
|
|
558
|
+
}
|
|
559
|
+
function sendWrapper(res, id, accountId, initialPath = "") {
|
|
560
|
+
if (closed || !devices.has(id)) {
|
|
561
|
+
res.writeHead(503).end();
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (capabilities.size >= RELAY_LIMITS.sessions) {
|
|
565
|
+
res.writeHead(503).end();
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
const token = randomBytes(32).toString("hex");
|
|
569
|
+
capabilities.set(token, { deviceId: id, accountId, expiresAt: Date.now() + 8 * 60 * 60_000 });
|
|
570
|
+
const wrapper = wrapperHtml(capabilityBase(id, token), initialPath);
|
|
571
|
+
res
|
|
572
|
+
.writeHead(200, {
|
|
573
|
+
"content-type": "text/html; charset=utf-8",
|
|
574
|
+
"content-security-policy": wrapper.csp,
|
|
575
|
+
"cache-control": "no-store",
|
|
576
|
+
"referrer-policy": "no-referrer",
|
|
577
|
+
"x-content-type-options": "nosniff",
|
|
578
|
+
})
|
|
579
|
+
.end(wrapper.html);
|
|
580
|
+
}
|
|
581
|
+
async function accountWrapper(req, res, id) {
|
|
582
|
+
const generation = revision;
|
|
583
|
+
try {
|
|
584
|
+
if (req.headers.origin === "null" ||
|
|
585
|
+
req.headers["sec-fetch-dest"] === "iframe" ||
|
|
586
|
+
(req.headers.origin && req.headers.origin !== hub.origin)) {
|
|
587
|
+
res.writeHead(401).end();
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
const account = await options.getAccount(req);
|
|
591
|
+
const accountId = typeof account === "string" ? account : account?.id;
|
|
592
|
+
if (!accountId || !(await options.ownsDevice(accountId, id))) {
|
|
593
|
+
res.writeHead(401).end();
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (generation !== revision || closed || res.destroyed) {
|
|
597
|
+
res.writeHead(403).end();
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
sendWrapper(res, id, accountId);
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
if (!res.headersSent)
|
|
604
|
+
res.writeHead(401).end();
|
|
605
|
+
else
|
|
606
|
+
res.destroy();
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
function handleRequest(req, res) {
|
|
610
|
+
const id = deviceId(req);
|
|
611
|
+
if (!id) {
|
|
612
|
+
if (domain && req.headers.host?.toLowerCase().endsWith(`.${domain}`)) {
|
|
613
|
+
res.writeHead(403).end();
|
|
614
|
+
return true;
|
|
615
|
+
}
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
618
|
+
res.setHeader("Cache-Control", "no-store");
|
|
619
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
620
|
+
const path = pathRequest(req);
|
|
621
|
+
const url = new URL(req.url || "/", path ? hub.origin : origin(id));
|
|
622
|
+
if (path && !path.token && path.tail !== "/__open") {
|
|
623
|
+
if (path.tail !== "/" || req.method !== "GET")
|
|
624
|
+
res.writeHead(404).end();
|
|
625
|
+
else
|
|
626
|
+
void accountWrapper(req, res, id);
|
|
627
|
+
return true;
|
|
628
|
+
}
|
|
629
|
+
if ((path && path.tail === "/__open") || (!path && url.pathname === "/__device/open")) {
|
|
630
|
+
const key = url.searchParams.get("ticket") || "";
|
|
631
|
+
const ticket = tickets.get(key);
|
|
632
|
+
if (req.method !== "GET" ||
|
|
633
|
+
!ticket ||
|
|
634
|
+
ticket.deviceId !== id ||
|
|
635
|
+
ticket.generation !== revision ||
|
|
636
|
+
ticket.expiresAt <= Date.now() ||
|
|
637
|
+
!devices.has(id) ||
|
|
638
|
+
sessions.size >= RELAY_LIMITS.sessions) {
|
|
639
|
+
res.writeHead(403).end();
|
|
640
|
+
return true;
|
|
641
|
+
}
|
|
642
|
+
tickets.delete(key);
|
|
643
|
+
if (path) {
|
|
644
|
+
sendWrapper(res, id, ticket.accountId, url.searchParams.get("next") === "/desktop" ? "desktop" : "");
|
|
645
|
+
return true;
|
|
646
|
+
}
|
|
647
|
+
const token = randomBytes(32).toString("hex");
|
|
648
|
+
sessions.set(token, { deviceId: id, expiresAt: Date.now() + 15 * 60_000 });
|
|
649
|
+
res
|
|
650
|
+
.writeHead(302, {
|
|
651
|
+
"set-cookie": `${deviceCookie(id)}=${token}; Path=/; Max-Age=900;${hub.protocol === "https:" ? " Secure;" : ""} HttpOnly; SameSite=Lax`,
|
|
652
|
+
location: url.searchParams.get("next") === "/desktop" ? "/desktop" : "/",
|
|
653
|
+
})
|
|
654
|
+
.end();
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
if (!(path ? pathAuthorized(req, id) : authorized(req, id))) {
|
|
658
|
+
res.writeHead(403).end();
|
|
659
|
+
return true;
|
|
660
|
+
}
|
|
661
|
+
if (path && req.method === "OPTIONS") {
|
|
662
|
+
res.writeHead(204, portalHeaders(hub, capabilityBase(id, path.token))).end();
|
|
663
|
+
return true;
|
|
664
|
+
}
|
|
665
|
+
// Only authenticated capability requests receive opaque-origin response headers.
|
|
666
|
+
if (path) {
|
|
667
|
+
for (const [key, value] of Object.entries(portalHeaders(hub, capabilityBase(id, path.token))))
|
|
668
|
+
res.setHeader(key, value);
|
|
669
|
+
}
|
|
670
|
+
const forwardPath = path ? path.path : req.url;
|
|
671
|
+
// Serve account binding at the Hub, including compatibility for older device UIs.
|
|
672
|
+
// Never forward the local management status endpoint or expose its settings.
|
|
673
|
+
if (path &&
|
|
674
|
+
req.method === "GET" &&
|
|
675
|
+
["/api/device-center/chat-status", "/api/device-center/status"].includes(forwardPath?.split("?")[0] ?? "")) {
|
|
676
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
677
|
+
res.end(JSON.stringify({ hubUrl: hub.origin, deviceId: id }));
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
const entry = devices.get(id);
|
|
681
|
+
if (!entry || entry.streams.size >= RELAY_LIMITS.streams) {
|
|
682
|
+
res.writeHead(503).end();
|
|
683
|
+
return true;
|
|
684
|
+
}
|
|
685
|
+
if (!safePath(forwardPath, req.method)) {
|
|
686
|
+
res.writeHead(400).end();
|
|
687
|
+
return true;
|
|
688
|
+
}
|
|
689
|
+
// Only entry documents are rewritten; preserve negotiated compression for assets.
|
|
690
|
+
const rewriteHtml = !!path && ["/", "/desktop"].includes(path.path.split("?")[0]);
|
|
691
|
+
const streamId = randomBytes(12).toString("hex");
|
|
692
|
+
addStream(entry, streamId, {
|
|
693
|
+
res,
|
|
694
|
+
...(path
|
|
695
|
+
? {
|
|
696
|
+
portal: createPortalResponse(res, hub, capabilityBase(id, path.token), rewriteHtml),
|
|
697
|
+
}
|
|
698
|
+
: {}),
|
|
699
|
+
});
|
|
700
|
+
let bytes = 0;
|
|
701
|
+
sendFrame(entry.ws, {
|
|
702
|
+
type: "request",
|
|
703
|
+
id: streamId,
|
|
704
|
+
method: req.method,
|
|
705
|
+
path: forwardPath,
|
|
706
|
+
headers: { ...cleanHeaders(req.headers), ...(rewriteHtml ? { "accept-encoding": "identity" } : {}) },
|
|
707
|
+
});
|
|
708
|
+
req.on("data", (chunk) => {
|
|
709
|
+
bytes += chunk.length;
|
|
710
|
+
if (bytes > RELAY_LIMITS.body || !sendChunks(entry.ws, "request_body", streamId, chunk)) {
|
|
711
|
+
sendFrame(entry.ws, { type: "cancel", id: streamId });
|
|
712
|
+
req.destroy();
|
|
713
|
+
}
|
|
714
|
+
});
|
|
715
|
+
req.on("end", () => sendFrame(entry.ws, { type: "request_end", id: streamId }));
|
|
716
|
+
res.on("close", () => {
|
|
717
|
+
const item = entry.streams.get(streamId);
|
|
718
|
+
if (item) {
|
|
719
|
+
clearTimeout(item.timer);
|
|
720
|
+
entry.streams.delete(streamId);
|
|
721
|
+
sendFrame(entry.ws, { type: "cancel", id: streamId });
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
req.on("error", () => res.destroy());
|
|
725
|
+
req.on("aborted", () => res.destroy());
|
|
726
|
+
return true;
|
|
727
|
+
}
|
|
728
|
+
async function upgrade(req, socket, head) {
|
|
729
|
+
const id = deviceId(req);
|
|
730
|
+
if (!id && domain && req.headers.host?.toLowerCase().endsWith(`.${domain}`)) {
|
|
731
|
+
socket.destroy();
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
if (id) {
|
|
735
|
+
const path = pathRequest(req);
|
|
736
|
+
const entry = devices.get(id);
|
|
737
|
+
if (!entry ||
|
|
738
|
+
!(path ? pathAuthorized(req, id, true) : authorized(req, id, true)) ||
|
|
739
|
+
entry.streams.size >= RELAY_LIMITS.streams ||
|
|
740
|
+
!safePath(path ? path.path : req.url, "WS")) {
|
|
741
|
+
socket.destroy();
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
browserWss.handleUpgrade(req, socket, head, (ws) => {
|
|
745
|
+
const streamId = randomBytes(12).toString("hex");
|
|
746
|
+
addStream(entry, streamId, { ws });
|
|
747
|
+
ws.pause();
|
|
748
|
+
sendFrame(entry.ws, {
|
|
749
|
+
type: "ws_open",
|
|
750
|
+
id: streamId,
|
|
751
|
+
path: path ? path.path : req.url,
|
|
752
|
+
headers: cleanHeaders(req.headers),
|
|
753
|
+
protocols: req.headers["sec-websocket-protocol"],
|
|
754
|
+
});
|
|
755
|
+
ws.on("message", (data, binary) => {
|
|
756
|
+
const buffer = Buffer.from(data);
|
|
757
|
+
if (!entry.messages.send(streamId, buffer, binary))
|
|
758
|
+
ws.terminate();
|
|
759
|
+
});
|
|
760
|
+
ws.on("close", () => {
|
|
761
|
+
const item = entry.streams.get(streamId);
|
|
762
|
+
if (item) {
|
|
763
|
+
clearTimeout(item.timer);
|
|
764
|
+
entry.messages.discard(streamId);
|
|
765
|
+
entry.streams.delete(streamId);
|
|
766
|
+
sendFrame(entry.ws, { type: "ws_close", id: streamId });
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
ws.on("error", () => ws.terminate());
|
|
770
|
+
});
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
let url;
|
|
774
|
+
try {
|
|
775
|
+
url = new URL(req.url || "/", hub);
|
|
776
|
+
}
|
|
777
|
+
catch {
|
|
778
|
+
socket.destroy();
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
if (url.pathname !== "/device-connect")
|
|
782
|
+
return;
|
|
783
|
+
const device = url.searchParams.get("deviceId") || "";
|
|
784
|
+
const credential = req.headers.authorization?.match(/^Bearer (\S+)$/)?.[1];
|
|
785
|
+
if (authenticating >= RELAY_LIMITS.devices) {
|
|
786
|
+
socket.destroy();
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
authenticating++;
|
|
790
|
+
const generation = revision;
|
|
791
|
+
try {
|
|
792
|
+
if (closed ||
|
|
793
|
+
req.headers.host !== hub.host ||
|
|
794
|
+
req.headers.origin ||
|
|
795
|
+
!/^[a-z0-9][a-z0-9-]{0,62}$/.test(device) ||
|
|
796
|
+
!credential ||
|
|
797
|
+
credential.length > 4096 ||
|
|
798
|
+
!(await options.authenticateDevice(device, credential)) ||
|
|
799
|
+
(devices.size >= RELAY_LIMITS.devices && !devices.has(device)) ||
|
|
800
|
+
socket.destroyed ||
|
|
801
|
+
generation !== revision ||
|
|
802
|
+
closed) {
|
|
803
|
+
socket.destroy();
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
807
|
+
const old = devices.get(device);
|
|
808
|
+
if (old) {
|
|
809
|
+
drop(device, old);
|
|
810
|
+
old.ws.terminate();
|
|
811
|
+
}
|
|
812
|
+
const entry = {
|
|
813
|
+
ws,
|
|
814
|
+
streams: new Map(),
|
|
815
|
+
tasks: new Map(),
|
|
816
|
+
rpc: createCommandChannel(ws),
|
|
817
|
+
messages: createWsMessageChannel(ws),
|
|
818
|
+
};
|
|
819
|
+
devices.set(device, entry);
|
|
820
|
+
alive.add(ws);
|
|
821
|
+
ws.on("pong", () => alive.add(ws));
|
|
822
|
+
ws.on("message", (raw) => {
|
|
823
|
+
try {
|
|
824
|
+
if (devices.get(device) !== entry)
|
|
825
|
+
return;
|
|
826
|
+
const frame = parseFrame(Buffer.from(raw));
|
|
827
|
+
if (entry.rpc.handle(frame))
|
|
828
|
+
return;
|
|
829
|
+
if (frame.type === "task_event") {
|
|
830
|
+
if (typeof frame.taskId !== "string" ||
|
|
831
|
+
typeof frame.botId !== "string" ||
|
|
832
|
+
entry.tasks.get(frame.taskId)?.attemptId !== frame.attemptId ||
|
|
833
|
+
entry.tasks.get(frame.taskId)?.botId !== frame.botId ||
|
|
834
|
+
!["running", "completed", "failed"].includes(String(frame.status)))
|
|
835
|
+
throw new Error("Unknown task");
|
|
836
|
+
if (frame.status === "completed" || frame.status === "failed")
|
|
837
|
+
entry.tasks.delete(frame.taskId);
|
|
838
|
+
Promise.resolve()
|
|
839
|
+
.then(() => options.onTaskEvent?.(device, frame))
|
|
840
|
+
.catch(() => ws.terminate());
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
const item = entry.streams.get(frame.id);
|
|
844
|
+
if (!item)
|
|
845
|
+
return;
|
|
846
|
+
if (frame.type === "response") {
|
|
847
|
+
const status = Number(frame.status);
|
|
848
|
+
if (!Number.isInteger(status) || status < 200 || status > 599 || !item.res || item.res.headersSent)
|
|
849
|
+
throw new Error("Invalid response");
|
|
850
|
+
const headers = cleanHeaders((frame.headers || {}));
|
|
851
|
+
if (item.portal)
|
|
852
|
+
item.portal.start(status, headers);
|
|
853
|
+
else {
|
|
854
|
+
item.res.writeHead(status, headers);
|
|
855
|
+
item.res.flushHeaders();
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else if (frame.type === "response_body") {
|
|
859
|
+
const data = decodeChunk(frame.data);
|
|
860
|
+
item.bytes += data.length;
|
|
861
|
+
if (item.bytes <= RELAY_LIMITS.body) {
|
|
862
|
+
if (item.portal)
|
|
863
|
+
item.portal.write(data);
|
|
864
|
+
else if (item.res?.headersSent)
|
|
865
|
+
item.res.write(data);
|
|
866
|
+
}
|
|
867
|
+
if (item.bytes > RELAY_LIMITS.body || (!item.portal && !item.res?.headersSent)) {
|
|
868
|
+
item.res?.destroy();
|
|
869
|
+
sendFrame(ws, { type: "cancel", id: frame.id });
|
|
870
|
+
}
|
|
871
|
+
else if (item.res && item.res.writableLength > RELAY_LIMITS.queue / 2) {
|
|
872
|
+
pauseForResponse(ws, item.res);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
else if (frame.type === "response_end" || frame.type === "error") {
|
|
876
|
+
if (frame.type === "error")
|
|
877
|
+
item.res?.destroy();
|
|
878
|
+
else if (item.portal)
|
|
879
|
+
item.portal.end();
|
|
880
|
+
else
|
|
881
|
+
item.res?.end();
|
|
882
|
+
item.ws?.terminate();
|
|
883
|
+
clearTimeout(item.timer);
|
|
884
|
+
entry.streams.delete(frame.id);
|
|
885
|
+
}
|
|
886
|
+
else if (frame.type === "ws_ready") {
|
|
887
|
+
item.ws?.resume();
|
|
888
|
+
}
|
|
889
|
+
else if (frame.type === "ws_chunk" || frame.type === "ws_end") {
|
|
890
|
+
if (!item.ws)
|
|
891
|
+
throw new Error("Missing WS stream");
|
|
892
|
+
entry.messages.receive(frame, item.ws);
|
|
893
|
+
}
|
|
894
|
+
else if (frame.type === "ws_close")
|
|
895
|
+
item.ws?.close();
|
|
896
|
+
}
|
|
897
|
+
catch {
|
|
898
|
+
ws.terminate();
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
ws.on("close", () => drop(device, entry));
|
|
902
|
+
ws.on("error", () => ws.terminate());
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
catch {
|
|
906
|
+
socket.destroy();
|
|
907
|
+
}
|
|
908
|
+
finally {
|
|
909
|
+
authenticating--;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
const upgradeListener = (req, socket, head) => {
|
|
913
|
+
void upgrade(req, socket, head);
|
|
914
|
+
};
|
|
915
|
+
options.server.on("upgrade", upgradeListener);
|
|
916
|
+
const heartbeat = setInterval(() => {
|
|
917
|
+
const now = Date.now();
|
|
918
|
+
for (const map of [tickets, sessions, capabilities])
|
|
919
|
+
for (const [key, value] of map)
|
|
920
|
+
if (value.expiresAt <= now)
|
|
921
|
+
map.delete(key);
|
|
922
|
+
for (const entry of devices.values()) {
|
|
923
|
+
if (!alive.has(entry.ws)) {
|
|
924
|
+
entry.ws.terminate();
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
alive.delete(entry.ws);
|
|
928
|
+
entry.ws.ping();
|
|
929
|
+
}
|
|
930
|
+
}, 15_000);
|
|
931
|
+
heartbeat.unref();
|
|
932
|
+
return {
|
|
933
|
+
callDevice(id, action, payload, options) {
|
|
934
|
+
const entry = devices.get(id);
|
|
935
|
+
return entry ? entry.rpc.call(action, payload, options) : Promise.reject(new Error("Device offline"));
|
|
936
|
+
},
|
|
937
|
+
handleRequest,
|
|
938
|
+
handleOpen,
|
|
939
|
+
handleAliasOpen: (req, res, id) => handleOpen(req, res, id, true),
|
|
940
|
+
handleUpgrade: (req, socket, head) => {
|
|
941
|
+
if (!deviceId(req)) {
|
|
942
|
+
socket.destroy();
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
void upgrade(req, socket, head);
|
|
946
|
+
},
|
|
947
|
+
isDeviceRequest: (req) => !!deviceId(req) || !!(domain && req.headers.host?.toLowerCase().endsWith(`.${domain}`)),
|
|
948
|
+
isOnline: (id) => devices.get(id)?.ws.readyState === WebSocket.OPEN,
|
|
949
|
+
sendTask(id, task) {
|
|
950
|
+
const entry = devices.get(id);
|
|
951
|
+
if (!entry ||
|
|
952
|
+
typeof task?.id !== "string" ||
|
|
953
|
+
typeof task.attemptId !== "string" ||
|
|
954
|
+
typeof task.botId !== "string" ||
|
|
955
|
+
!task.botId ||
|
|
956
|
+
task.deviceId !== id ||
|
|
957
|
+
!Number.isSafeInteger(task.botRevision) ||
|
|
958
|
+
task.botRevision < 1 ||
|
|
959
|
+
entry.tasks.has(task.id) ||
|
|
960
|
+
entry.tasks.size >= RELAY_LIMITS.streams)
|
|
961
|
+
return false;
|
|
962
|
+
entry.tasks.set(task.id, { attemptId: task.attemptId, botId: task.botId });
|
|
963
|
+
if (!sendFrame(entry.ws, { type: "task", task })) {
|
|
964
|
+
entry.tasks.delete(task.id);
|
|
965
|
+
return false;
|
|
966
|
+
}
|
|
967
|
+
return true;
|
|
968
|
+
},
|
|
969
|
+
revoke(id) {
|
|
970
|
+
revision++;
|
|
971
|
+
for (const map of [tickets, sessions, capabilities])
|
|
972
|
+
for (const [key, value] of map)
|
|
973
|
+
if (value.deviceId === id)
|
|
974
|
+
map.delete(key);
|
|
975
|
+
const entry = devices.get(id);
|
|
976
|
+
if (entry) {
|
|
977
|
+
drop(id, entry);
|
|
978
|
+
entry.ws.terminate();
|
|
979
|
+
}
|
|
980
|
+
},
|
|
981
|
+
close() {
|
|
982
|
+
closed = true;
|
|
983
|
+
clearInterval(heartbeat);
|
|
984
|
+
options.server.off("upgrade", upgradeListener);
|
|
985
|
+
for (const [id, entry] of devices) {
|
|
986
|
+
drop(id, entry);
|
|
987
|
+
entry.ws.terminate();
|
|
988
|
+
}
|
|
989
|
+
tickets.clear();
|
|
990
|
+
sessions.clear();
|
|
991
|
+
capabilities.clear();
|
|
992
|
+
wss.close();
|
|
993
|
+
browserWss.close();
|
|
994
|
+
},
|
|
995
|
+
};
|
|
996
|
+
}
|