pi-web-ui 0.113.0 → 0.114.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -1
- package/README.md +117 -252
- package/README.zh-CN.md +145 -223
- package/README.zh-TW.md +145 -223
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +145 -20
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2296 -1121
- 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 +18 -8
- package/dist/server/canvas/canvas-agent-tool.js +65 -15
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +516 -199
- 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 +104 -22
- 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/control-socket.js +6 -2
- 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 +332 -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 +829 -0
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +476 -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 +959 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/smoke-preview.js +3 -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 +83 -27
- package/dist/server/dsh/dsh-agent-service.js +277 -158
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/durable/durable-agent-service.js +1 -1
- 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 +110 -34
- 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 +236 -232
- 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/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- 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 +262 -92
- package/dist/server/preset-fields.js +49 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +112 -72
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +160 -67
- package/dist/server/request-context.js +164 -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/scheduler-tasks.js +63 -48
- 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 +267 -111
- package/dist/server/setup-config.js +58 -0
- 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/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +47 -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/session-store.js +48 -6
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +334 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/webui-context.js +6 -6
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- package/docs/device-center.md +142 -0
- package/docs/device-desktop.md +48 -0
- package/package.json +4 -1
- package/plugin-sdk/index.d.ts +45 -9
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +1 -1
- package/themes/aetheris.css +1 -107
- package/themes/ayu-light.css +5 -29
- package/themes/bases/flow-base.css +0 -6
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +1 -0
- package/themes/bases/zhupi-base.css +1 -0
- package/themes/catppuccin-latte.css +4 -27
- package/themes/catppuccin.css +4 -35
- package/themes/claude-code-dark.css +1 -0
- package/themes/codex.css +4 -28
- package/themes/cyberpunk.css +3 -61
- package/themes/dark-teal.css +0 -1
- package/themes/dazzle.css +3 -73
- package/themes/everforest-light.css +4 -27
- package/themes/geist.css +4 -28
- package/themes/gruvbox-light.css +4 -27
- package/themes/kanagawa-lotus.css +4 -27
- package/themes/md-preview.css +3 -213
- package/themes/mist.css +4 -24
- package/themes/nord.css +4 -35
- package/themes/one-dark.css +4 -37
- package/themes/paper.css +4 -16
- package/themes/rose-pine-dawn.css +4 -28
- package/themes/sakura.css +4 -24
- package/themes/solarized-light.css +4 -27
- package/themes/tokyo-night.css +3 -34
- package/themes/white.css +4 -26
- package/themes/zhujian-dark.css +1 -0
- package/themes/zhupi-dark.css +1 -0
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
- package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
- package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
- package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
- package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
- package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
- package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
- package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
- package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
- package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
- package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
- package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
- package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
- package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
- package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
- package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
- package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
- package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
- package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
- package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
- package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
- package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
- package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
- package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
- package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
- package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/index-CPgAH5q7.js +83 -0
- package/web/dist/assets/index-Cje8iugL.js +83 -0
- package/web/dist/assets/index-DnKeiDbj.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-CqA4yW6w.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-BqdAjEjF.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +15 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
- package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
- package/web/dist/assets/index-BwL7qBh6.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
|
@@ -0,0 +1,829 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
|
+
import { DeviceHubStore, hashSecret, isTerminal, publicDevice, secretMatches } from "./store.js";
|
|
5
|
+
import { createAccountAuth, hashPassword, verifyPassword, SESSION_TTL, HubRateLimiter } from "./hub-auth.js";
|
|
6
|
+
class HttpError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
constructor(status, message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.status = status;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function fail(status, message) {
|
|
14
|
+
throw new HttpError(status, message);
|
|
15
|
+
}
|
|
16
|
+
function text(value, max = 16384) {
|
|
17
|
+
if (typeof value !== "string" || !value.trim() || Buffer.byteLength(value) > max)
|
|
18
|
+
fail(400, "Invalid text");
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
function ids(value) {
|
|
22
|
+
if (!Array.isArray(value) ||
|
|
23
|
+
value.length > 32 ||
|
|
24
|
+
value.some((id) => typeof id !== "string" || id.length > 128) ||
|
|
25
|
+
new Set(value).size !== value.length)
|
|
26
|
+
fail(400, "Invalid botIds");
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function handoff(value) {
|
|
30
|
+
if (value === undefined)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
33
|
+
fail(400, "Invalid handoff");
|
|
34
|
+
const v = value;
|
|
35
|
+
return {
|
|
36
|
+
repository: text(v.repository, 2048),
|
|
37
|
+
commit: text(v.commit, 128),
|
|
38
|
+
...(v.branch === undefined ? {} : { branch: text(v.branch, 256) }),
|
|
39
|
+
instructions: text(v.instructions, 8192),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const token = () => randomBytes(32).toString("base64url");
|
|
43
|
+
const PAIR_TTL = 10 * 60 * 1000;
|
|
44
|
+
const HISTORY = 500;
|
|
45
|
+
/** Does not listen. The caller may attach a relay, root page and additional routes before listening. */
|
|
46
|
+
export async function createDeviceHub(options) {
|
|
47
|
+
const origin = new URL(options.publicUrl);
|
|
48
|
+
if (!["http:", "https:"].includes(origin.protocol) ||
|
|
49
|
+
origin.pathname !== "/" ||
|
|
50
|
+
origin.search ||
|
|
51
|
+
origin.hash ||
|
|
52
|
+
origin.username ||
|
|
53
|
+
origin["pass" + "word"] ||
|
|
54
|
+
options.publicUrl !== origin.origin)
|
|
55
|
+
throw new Error("publicUrl must be a canonical root origin");
|
|
56
|
+
if (options.deviceDomain !== undefined) {
|
|
57
|
+
const domain = new URL(`https://${options.deviceDomain}`);
|
|
58
|
+
if (domain.host !== options.deviceDomain ||
|
|
59
|
+
domain.pathname !== "/" ||
|
|
60
|
+
!/^[a-z0-9.-]+(?::[0-9]{1,5})?$/i.test(options.deviceDomain))
|
|
61
|
+
throw new Error("Invalid deviceDomain");
|
|
62
|
+
if (origin.hostname === domain.hostname ||
|
|
63
|
+
origin.hostname.endsWith(`.${domain.hostname}`) ||
|
|
64
|
+
domain.hostname.endsWith(`.${origin.hostname}`))
|
|
65
|
+
throw new Error("Device domain must be independent of hub domain");
|
|
66
|
+
}
|
|
67
|
+
const store = await DeviceHubStore.open(options.dataDir);
|
|
68
|
+
const auth = createAccountAuth(store, options.publicUrl);
|
|
69
|
+
const getAccount = (req) => auth.getAccount(req);
|
|
70
|
+
async function authenticateAgent(req) {
|
|
71
|
+
const deviceId = req.headers["x-device-id"];
|
|
72
|
+
const authorization = req.headers.authorization;
|
|
73
|
+
if (typeof deviceId !== "string" || !authorization?.startsWith("Bearer "))
|
|
74
|
+
return undefined;
|
|
75
|
+
if (!(await store.authenticateDevice(deviceId, authorization.slice(7))))
|
|
76
|
+
return undefined;
|
|
77
|
+
const device = store.getDevice(deviceId);
|
|
78
|
+
const owner = device && store.snapshot().accounts.find((a) => a.id === device.accountId);
|
|
79
|
+
return device && owner ? { device, account: { id: owner.id, username: owner.username } } : undefined;
|
|
80
|
+
}
|
|
81
|
+
const agents = new WeakMap();
|
|
82
|
+
const users = new WeakMap();
|
|
83
|
+
const agentWrites = new HubRateLimiter(30, 60000);
|
|
84
|
+
const account = (req) => {
|
|
85
|
+
const agent = agents.get(req) ?? users.get(req);
|
|
86
|
+
if (agent) {
|
|
87
|
+
if (store.getDeviceOwner(agent.device.id) !== agent.account.id)
|
|
88
|
+
fail(401, "Device revoked");
|
|
89
|
+
return agent.account;
|
|
90
|
+
}
|
|
91
|
+
return getAccount(req) ?? fail(401, "Authentication required");
|
|
92
|
+
};
|
|
93
|
+
const app = express();
|
|
94
|
+
app.disable("x-powered-by");
|
|
95
|
+
app.use((req, _res, next) => {
|
|
96
|
+
if (!req.path.startsWith("/api/device-user/"))
|
|
97
|
+
return next();
|
|
98
|
+
const deviceId = req.headers["x-device-id"];
|
|
99
|
+
const device = typeof deviceId === "string" ? store.snapshot().devices.find((d) => d.id === deviceId) : undefined;
|
|
100
|
+
const owner = device && store.snapshot().accounts.find((a) => a.id === device.accountId);
|
|
101
|
+
const bearer = req.headers.authorization;
|
|
102
|
+
if (!device?.uiCredentialHash ||
|
|
103
|
+
!owner ||
|
|
104
|
+
!bearer?.startsWith("Bearer ") ||
|
|
105
|
+
!secretMatches(bearer.slice(7), device.uiCredentialHash))
|
|
106
|
+
fail(401, "UI device authentication required; pair again");
|
|
107
|
+
if (req.method === "POST" && !agentWrites.allow("user:" + device.id))
|
|
108
|
+
fail(429, "Too many user writes");
|
|
109
|
+
const suffix = req.path.slice("/api/device-user".length);
|
|
110
|
+
if (!((req.method === "GET" && (["/devices", "/bots", "/rooms"].includes(suffix) || /^\/rooms\/[^/]+$/.test(suffix))) ||
|
|
111
|
+
(req.method === "POST" &&
|
|
112
|
+
(suffix === "/rooms" ||
|
|
113
|
+
/^\/rooms\/[^/]+\/(messages|rename|members|delete)$/.test(suffix) ||
|
|
114
|
+
/^\/devices\/[^/]+\/open$/.test(suffix)))))
|
|
115
|
+
fail(404, "User route missing");
|
|
116
|
+
users.set(req, { device, account: { id: owner.id, username: owner.username } });
|
|
117
|
+
req.url = req.url.replace("/api/device-user/", "/api/");
|
|
118
|
+
next();
|
|
119
|
+
});
|
|
120
|
+
app.use(async (req, _res, next) => {
|
|
121
|
+
if (!req.path.startsWith("/api/agent/"))
|
|
122
|
+
return next();
|
|
123
|
+
const agent = await authenticateAgent(req);
|
|
124
|
+
if (!agent)
|
|
125
|
+
fail(401, "Device authentication required");
|
|
126
|
+
if (["POST", "PUT"].includes(req.method) && !agentWrites.allow(agent.device.id))
|
|
127
|
+
fail(429, "Too many device writes");
|
|
128
|
+
agents.set(req, agent);
|
|
129
|
+
const suffix = req.path.slice("/api/agent".length);
|
|
130
|
+
if ((req.method === "GET" && (["/devices", "/bots", "/rooms"].includes(suffix) || /^\/rooms\/[^/]+$/.test(suffix))) ||
|
|
131
|
+
(req.method === "POST" && (suffix === "/rooms" || /^\/rooms\/[^/]+\/messages$/.test(suffix))))
|
|
132
|
+
req.url = req.url.replace("/api/agent/", "/api/");
|
|
133
|
+
else if (!((suffix === "/transfers" && req.method === "POST") || (suffix === "/bots" && req.method === "PUT")))
|
|
134
|
+
fail(404, "Agent route missing");
|
|
135
|
+
next();
|
|
136
|
+
});
|
|
137
|
+
app.use((req, res, next) => {
|
|
138
|
+
if (req.headers.host !== origin.host)
|
|
139
|
+
return res.status(421).json({ error: "Host rejected" });
|
|
140
|
+
if (!agents.has(req) &&
|
|
141
|
+
!users.has(req) &&
|
|
142
|
+
!["GET", "HEAD", "OPTIONS"].includes(req.method) &&
|
|
143
|
+
req.headers.origin !== options.publicUrl)
|
|
144
|
+
return res.status(403).json({ error: "Origin rejected" });
|
|
145
|
+
next();
|
|
146
|
+
});
|
|
147
|
+
const json = express.json({ limit: "32kb", strict: true });
|
|
148
|
+
app.use((req, res, next) => {
|
|
149
|
+
if (agents.has(req) && req.path === "/api/agent/transfers")
|
|
150
|
+
return next();
|
|
151
|
+
json(req, res, next);
|
|
152
|
+
});
|
|
153
|
+
const loginLimit = new HubRateLimiter(10, 60000);
|
|
154
|
+
const pairLimit = new HubRateLimiter(20, 60000);
|
|
155
|
+
const pairs = new Map();
|
|
156
|
+
const sweepPairs = () => {
|
|
157
|
+
for (const [key, value] of pairs)
|
|
158
|
+
if (value.expiresAt <= Date.now())
|
|
159
|
+
pairs.delete(key);
|
|
160
|
+
};
|
|
161
|
+
const ip = (req) => req.socket.remoteAddress ?? "unknown";
|
|
162
|
+
const visibleDevice = (device) => ({
|
|
163
|
+
id: device.id,
|
|
164
|
+
accountId: device.accountId,
|
|
165
|
+
name: device.name,
|
|
166
|
+
createdAt: device.createdAt,
|
|
167
|
+
online: options.isOnline?.(device.id) ?? false,
|
|
168
|
+
url: (options.pathAccess ? `${origin.origin}/device/${encodeURIComponent(device.id)}/` : undefined) ??
|
|
169
|
+
options.portals?.getOrigin(device.id) ??
|
|
170
|
+
(options.deviceDomain ? `${origin.protocol}//${device.id}.${options.deviceDomain}` : null),
|
|
171
|
+
alias: options.portals?.getAlias(device.id) ?? null,
|
|
172
|
+
});
|
|
173
|
+
for (const route of ["/api/me", "/api/auth/me"])
|
|
174
|
+
app.get(route, (req, res) => res.json({ account: account(req) }));
|
|
175
|
+
app.post("/api/auth/register", async (req, res) => {
|
|
176
|
+
if (!loginLimit.allow(ip(req)))
|
|
177
|
+
fail(429, "Too many attempts");
|
|
178
|
+
if (options.allowRegistration === false)
|
|
179
|
+
fail(403, "Registration disabled");
|
|
180
|
+
const username = text(req.body?.username, 64).trim().toLowerCase();
|
|
181
|
+
if (!/^[a-z0-9_.-]{3,64}$/.test(username))
|
|
182
|
+
fail(400, "Invalid username");
|
|
183
|
+
const password = text(req.body?.["pass" + "word"], 1024);
|
|
184
|
+
if (password.length < 8)
|
|
185
|
+
fail(400, "Password too short");
|
|
186
|
+
const passwordHash = await hashPassword(password);
|
|
187
|
+
const sessionToken = token();
|
|
188
|
+
const created = await store.transact((draft) => {
|
|
189
|
+
if (draft.accounts.some((entry) => entry.username === username))
|
|
190
|
+
fail(409, "Username unavailable");
|
|
191
|
+
if (draft.accounts.length >= 10000)
|
|
192
|
+
fail(409, "Account capacity reached");
|
|
193
|
+
const entry = { id: randomUUID(), username, passwordHash, createdAt: Date.now() };
|
|
194
|
+
draft.accounts.push(entry);
|
|
195
|
+
draft.sessions = draft.sessions.filter((s) => s.expiresAt > Date.now());
|
|
196
|
+
draft.sessions.push({ accountId: entry.id, hash: hashSecret(sessionToken), expiresAt: Date.now() + SESSION_TTL });
|
|
197
|
+
return { id: entry.id, username };
|
|
198
|
+
});
|
|
199
|
+
res.setHeader("Set-Cookie", auth.cookie(sessionToken));
|
|
200
|
+
res.status(201).json({ account: created });
|
|
201
|
+
});
|
|
202
|
+
app.post("/api/auth/login", async (req, res) => {
|
|
203
|
+
if (!loginLimit.allow(ip(req)))
|
|
204
|
+
fail(429, "Too many attempts");
|
|
205
|
+
const username = text(req.body?.username, 64).trim().toLowerCase();
|
|
206
|
+
const password = text(req.body?.["pass" + "word"], 1024);
|
|
207
|
+
const entry = store.snapshot().accounts.find((item) => item.username === username);
|
|
208
|
+
// Run the same KDF for missing accounts, avoiding a cheap username oracle.
|
|
209
|
+
if (!(await verifyPassword(password, entry?.passwordHash ?? `scrypt:${"0".repeat(32)}:${"0".repeat(128)}`)) ||
|
|
210
|
+
!entry)
|
|
211
|
+
fail(401, "Invalid credentials");
|
|
212
|
+
const sessionToken = token();
|
|
213
|
+
await store.transact((draft) => {
|
|
214
|
+
draft.sessions = draft.sessions.filter((s) => s.expiresAt > Date.now());
|
|
215
|
+
if (draft.sessions.filter((s) => s.accountId === entry.id).length >= 100)
|
|
216
|
+
fail(429, "Session capacity reached");
|
|
217
|
+
draft.sessions.push({ accountId: entry.id, hash: hashSecret(sessionToken), expiresAt: Date.now() + SESSION_TTL });
|
|
218
|
+
});
|
|
219
|
+
res.setHeader("Set-Cookie", auth.cookie(sessionToken));
|
|
220
|
+
res.json({ account: { id: entry.id, username: entry.username } });
|
|
221
|
+
});
|
|
222
|
+
app.post("/api/auth/logout", async (req, res) => {
|
|
223
|
+
const value = auth.getToken(req);
|
|
224
|
+
await store.transact((draft) => {
|
|
225
|
+
draft.sessions = draft.sessions.filter((session) => session.hash !== hashSecret(value ?? ""));
|
|
226
|
+
});
|
|
227
|
+
res.setHeader("Set-Cookie", auth.cookie("", true));
|
|
228
|
+
res.json({ ok: true });
|
|
229
|
+
});
|
|
230
|
+
app.post("/api/pair/start", (req, res) => {
|
|
231
|
+
if (!pairLimit.allow(ip(req)))
|
|
232
|
+
fail(429, "Too many attempts");
|
|
233
|
+
sweepPairs();
|
|
234
|
+
if (pairs.size >= 1000)
|
|
235
|
+
fail(429, "Too many pending pairs");
|
|
236
|
+
const name = text(req.body?.name, 128);
|
|
237
|
+
const pollToken = token();
|
|
238
|
+
const code = randomBytes(6).toString("hex").toUpperCase();
|
|
239
|
+
const expiresAt = Date.now() + PAIR_TTL;
|
|
240
|
+
pairs.set(hashSecret(pollToken), { code, name, expiresAt });
|
|
241
|
+
res.json({ code, pollToken, expiresAt });
|
|
242
|
+
});
|
|
243
|
+
const approving = new Set();
|
|
244
|
+
app.post("/api/pair/approve", async (req, res) => {
|
|
245
|
+
const owner = account(req);
|
|
246
|
+
if (!pairLimit.allow(`approve:${ip(req)}`))
|
|
247
|
+
fail(429, "Too many attempts");
|
|
248
|
+
sweepPairs();
|
|
249
|
+
const code = text(req.body?.code, 64).toUpperCase();
|
|
250
|
+
const pair = [...pairs.values()].find((item) => item.code === code);
|
|
251
|
+
if (!pair)
|
|
252
|
+
fail(404, "Pair expired or missing");
|
|
253
|
+
if (approving.has(code))
|
|
254
|
+
fail(409, "Pair approval in progress");
|
|
255
|
+
approving.add(code);
|
|
256
|
+
try {
|
|
257
|
+
const credential = token();
|
|
258
|
+
const uiCredential = token();
|
|
259
|
+
const device = await store.transact((draft) => {
|
|
260
|
+
if (pair.deviceId || pair.expiresAt <= Date.now() || ![...pairs.values()].includes(pair))
|
|
261
|
+
fail(409, "Pair unavailable");
|
|
262
|
+
const device = {
|
|
263
|
+
id: randomUUID(),
|
|
264
|
+
accountId: owner.id,
|
|
265
|
+
name: pair.name,
|
|
266
|
+
credentialHash: hashSecret(credential),
|
|
267
|
+
uiCredentialHash: hashSecret(uiCredential),
|
|
268
|
+
createdAt: Date.now(),
|
|
269
|
+
};
|
|
270
|
+
draft.devices.push(device);
|
|
271
|
+
return device;
|
|
272
|
+
});
|
|
273
|
+
pair.deviceId = device.id;
|
|
274
|
+
pair.accountId = owner.id;
|
|
275
|
+
pair.credential = credential;
|
|
276
|
+
pair.uiCredential = uiCredential;
|
|
277
|
+
res.json({ device: visibleDevice(device) });
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
approving.delete(code);
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
app.post("/api/pair/poll", (req, res) => {
|
|
284
|
+
if (!pairLimit.allow(`poll:${ip(req)}`))
|
|
285
|
+
fail(429, "Too many attempts");
|
|
286
|
+
sweepPairs();
|
|
287
|
+
const key = hashSecret(text(req.body?.pollToken, 256));
|
|
288
|
+
const pair = pairs.get(key);
|
|
289
|
+
if (!pair)
|
|
290
|
+
fail(404, "Pair expired or consumed");
|
|
291
|
+
if (!pair.deviceId)
|
|
292
|
+
return res.status(202).json({ pending: true });
|
|
293
|
+
if (store.getDeviceOwner(pair.deviceId) !== pair.accountId) {
|
|
294
|
+
pairs.delete(key);
|
|
295
|
+
fail(404, "Device revoked");
|
|
296
|
+
}
|
|
297
|
+
pairs.delete(key);
|
|
298
|
+
res.json({ deviceId: pair.deviceId, credential: pair.credential, uiCredential: pair.uiCredential });
|
|
299
|
+
});
|
|
300
|
+
app.get("/api/info", (_req, res) => {
|
|
301
|
+
res.json({
|
|
302
|
+
transport: origin.protocol === "https:" ? "https" : "http",
|
|
303
|
+
deviceWebAccess: !!options.pathAccess || !!options.deviceDomain,
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
app.get("/api/devices", (req, res) => res.json({
|
|
307
|
+
devices: store
|
|
308
|
+
.snapshot()
|
|
309
|
+
.devices.filter((d) => d.accountId === account(req).id)
|
|
310
|
+
.map(visibleDevice),
|
|
311
|
+
}));
|
|
312
|
+
app.post("/api/devices/:id/revoke", async (req, res) => {
|
|
313
|
+
const owner = account(req);
|
|
314
|
+
const id = String(req.params.id);
|
|
315
|
+
await store.transact((draft) => {
|
|
316
|
+
if (!draft.devices.some((device) => device.id === id && device.accountId === owner.id))
|
|
317
|
+
fail(404, "Device missing");
|
|
318
|
+
draft.devices = draft.devices.filter((device) => device.id !== id);
|
|
319
|
+
const removedBots = new Set(draft.bots.filter((b) => b.deviceId === id).map((b) => b.id));
|
|
320
|
+
draft.bots = draft.bots.filter((b) => b.deviceId !== id);
|
|
321
|
+
for (const room of draft.rooms)
|
|
322
|
+
room.botIds = room.botIds.filter((botId) => !removedBots.has(botId));
|
|
323
|
+
for (const task of draft.tasks)
|
|
324
|
+
if (task.deviceId === id && !isTerminal(task.status)) {
|
|
325
|
+
task.status = "interrupted";
|
|
326
|
+
task.updatedAt = Date.now();
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
for (const [key, pair] of pairs)
|
|
330
|
+
if (pair.deviceId === id)
|
|
331
|
+
pairs.delete(key);
|
|
332
|
+
await (options.onRevoke ?? options.relay?.onRevoke)?.(id);
|
|
333
|
+
await options.portals?.retire(id);
|
|
334
|
+
res.json({ ok: true });
|
|
335
|
+
});
|
|
336
|
+
function ownBot(req, state) {
|
|
337
|
+
const agent = agents.get(req);
|
|
338
|
+
if (!agent)
|
|
339
|
+
return undefined;
|
|
340
|
+
const bot = state.bots.find((b) => b.id === req.body?.sourceBotId &&
|
|
341
|
+
b.deviceId === agent.device.id &&
|
|
342
|
+
b.accountId === agent.account.id &&
|
|
343
|
+
b.enabled);
|
|
344
|
+
if (!bot || !state.devices.some((d) => d.id === bot.deviceId && d.accountId === bot.accountId))
|
|
345
|
+
fail(403, "Source Bot access denied");
|
|
346
|
+
return bot;
|
|
347
|
+
}
|
|
348
|
+
const validBot = (state, id, accountId) => state.bots.find((b) => b.id === id &&
|
|
349
|
+
b.accountId === accountId &&
|
|
350
|
+
b.enabled &&
|
|
351
|
+
state.devices.some((d) => d.id === b.deviceId && d.accountId === accountId));
|
|
352
|
+
app.get("/api/bots", (req, res) => {
|
|
353
|
+
const owner = account(req);
|
|
354
|
+
const state = store.snapshot();
|
|
355
|
+
res.json({
|
|
356
|
+
bots: state.bots
|
|
357
|
+
.filter((b) => b.accountId === owner.id)
|
|
358
|
+
.map((b) => ({
|
|
359
|
+
...b,
|
|
360
|
+
deviceName: state.devices.find((device) => device.id === b.deviceId && device.accountId === owner.id)?.name,
|
|
361
|
+
online: options.isOnline?.(b.deviceId) ?? false,
|
|
362
|
+
})),
|
|
363
|
+
});
|
|
364
|
+
});
|
|
365
|
+
app.put("/api/agent/bots", async (req, res) => {
|
|
366
|
+
const owner = account(req);
|
|
367
|
+
const device = agents.get(req).device;
|
|
368
|
+
const rows = req.body?.bots;
|
|
369
|
+
if (!Array.isArray(rows) || rows.length > 128 || new Set(rows.map((b) => b?.id)).size !== rows.length)
|
|
370
|
+
fail(400, "Invalid Bots");
|
|
371
|
+
const incoming = rows.map((b) => {
|
|
372
|
+
const id = text(b?.id, 128), name = text(b?.name, 128);
|
|
373
|
+
if (typeof b?.description !== "string" ||
|
|
374
|
+
Buffer.byteLength(b.description) > 2048 ||
|
|
375
|
+
typeof b.enabled !== "boolean" ||
|
|
376
|
+
!Number.isSafeInteger(b.revision) ||
|
|
377
|
+
b.revision < 1)
|
|
378
|
+
fail(400, "Invalid Bot registration");
|
|
379
|
+
return { id, name, description: b.description, enabled: b.enabled, revision: b.revision };
|
|
380
|
+
});
|
|
381
|
+
const bots = await store.transact((draft) => {
|
|
382
|
+
if (!draft.devices.some((d) => d.id === device.id && d.accountId === owner.id))
|
|
383
|
+
fail(401, "Device revoked");
|
|
384
|
+
if (draft.tasks.some((task) => task.deviceId === device.id &&
|
|
385
|
+
!isTerminal(task.status) &&
|
|
386
|
+
!incoming.some((bot) => bot.id === task.botId && bot.enabled && bot.revision === task.botRevision)))
|
|
387
|
+
throw Object.assign(new Error("Stop active Bot tasks before changing registration"), {
|
|
388
|
+
status: 409,
|
|
389
|
+
code: "ACTIVE_TASKS",
|
|
390
|
+
});
|
|
391
|
+
for (const row of incoming) {
|
|
392
|
+
const previous = draft.bots.find((b) => b.id === row.id);
|
|
393
|
+
if (previous && (previous.deviceId !== device.id || previous.accountId !== owner.id))
|
|
394
|
+
fail(403, "Bot belongs to another device");
|
|
395
|
+
if (previous &&
|
|
396
|
+
(row.revision < previous.revision ||
|
|
397
|
+
(row.revision === previous.revision &&
|
|
398
|
+
["name", "description", "enabled"].some((k) => previous[k] !== row[k]))))
|
|
399
|
+
fail(409, "Bot revision is stale");
|
|
400
|
+
if (previous)
|
|
401
|
+
Object.assign(previous, row, { updatedAt: Date.now() });
|
|
402
|
+
else
|
|
403
|
+
draft.bots.push({
|
|
404
|
+
...row,
|
|
405
|
+
deviceId: device.id,
|
|
406
|
+
accountId: owner.id,
|
|
407
|
+
createdAt: Date.now(),
|
|
408
|
+
updatedAt: Date.now(),
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
for (const bot of draft.bots)
|
|
412
|
+
if (bot.deviceId === device.id && !incoming.some((b) => b.id === bot.id)) {
|
|
413
|
+
bot.enabled = false;
|
|
414
|
+
bot.updatedAt = Date.now();
|
|
415
|
+
}
|
|
416
|
+
return draft.bots.filter((b) => b.deviceId === device.id);
|
|
417
|
+
});
|
|
418
|
+
res.json({ bots });
|
|
419
|
+
});
|
|
420
|
+
app.get("/api/rooms", (req, res) => res.json({
|
|
421
|
+
rooms: store
|
|
422
|
+
.snapshot()
|
|
423
|
+
.rooms.filter((r) => r.accountId === account(req).id &&
|
|
424
|
+
(!agents.has(req) ||
|
|
425
|
+
store
|
|
426
|
+
.snapshot()
|
|
427
|
+
.bots.some((b) => b.enabled &&
|
|
428
|
+
b.deviceId === agents.get(req).device.id &&
|
|
429
|
+
b.accountId === r.accountId &&
|
|
430
|
+
r.botIds.includes(b.id)))),
|
|
431
|
+
}));
|
|
432
|
+
app.post("/api/rooms", async (req, res) => {
|
|
433
|
+
const owner = account(req), name = text(req.body?.name, 128), botIds = ids(req.body?.botIds ?? []);
|
|
434
|
+
const room = await store.transact((draft) => {
|
|
435
|
+
const source = ownBot(req, draft);
|
|
436
|
+
if (source && !botIds.includes(source.id))
|
|
437
|
+
fail(403, "Source Bot must be a member");
|
|
438
|
+
if (!botIds.length || botIds.some((id) => !validBot(draft, id, owner.id)))
|
|
439
|
+
fail(400, "Invalid room Bot");
|
|
440
|
+
if (draft.rooms.filter((r) => r.accountId === owner.id).length >= 100)
|
|
441
|
+
fail(409, "Room capacity reached");
|
|
442
|
+
const room = { id: randomUUID(), accountId: owner.id, name, botIds, createdAt: Date.now() };
|
|
443
|
+
draft.rooms.push(room);
|
|
444
|
+
return room;
|
|
445
|
+
});
|
|
446
|
+
res.status(201).json({ room });
|
|
447
|
+
});
|
|
448
|
+
app.get("/api/rooms/:id", (req, res) => {
|
|
449
|
+
const state = store.snapshot(), room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
|
|
450
|
+
if (!room ||
|
|
451
|
+
(agents.has(req) &&
|
|
452
|
+
!state.bots.some((b) => b.enabled &&
|
|
453
|
+
b.deviceId === agents.get(req).device.id &&
|
|
454
|
+
b.accountId === room.accountId &&
|
|
455
|
+
room.botIds.includes(b.id))))
|
|
456
|
+
fail(404, "Room missing");
|
|
457
|
+
res.json({
|
|
458
|
+
room,
|
|
459
|
+
bots: state.bots
|
|
460
|
+
.filter((b) => room.botIds.includes(b.id) && b.accountId === room.accountId)
|
|
461
|
+
.map((b) => ({
|
|
462
|
+
...b,
|
|
463
|
+
deviceName: state.devices.find((device) => device.id === b.deviceId && device.accountId === room.accountId)
|
|
464
|
+
?.name,
|
|
465
|
+
})),
|
|
466
|
+
messages: state.messages.filter((m) => m.roomId === room.id),
|
|
467
|
+
tasks: state.tasks.filter((t) => t.roomId === room.id),
|
|
468
|
+
});
|
|
469
|
+
});
|
|
470
|
+
for (const operation of ["rename", "members", "delete"]) {
|
|
471
|
+
app.post(`/api/rooms/:id/${operation}`, async (req, res) => {
|
|
472
|
+
const owner = account(req);
|
|
473
|
+
const result = await store.transact((draft) => {
|
|
474
|
+
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
475
|
+
if (!room)
|
|
476
|
+
fail(404, "Room missing");
|
|
477
|
+
if (operation === "rename")
|
|
478
|
+
room.name = text(req.body?.name, 128);
|
|
479
|
+
if (operation === "members") {
|
|
480
|
+
const members = ids(req.body?.botIds);
|
|
481
|
+
if (!members.length || members.some((id) => !validBot(draft, id, owner.id)))
|
|
482
|
+
fail(400, "Invalid room Bot");
|
|
483
|
+
if (draft.tasks.some((t) => t.roomId === room.id && !isTerminal(t.status) && !members.includes(t.botId)))
|
|
484
|
+
throw Object.assign(new Error("Stop removed Bots' active tasks first"), {
|
|
485
|
+
status: 409,
|
|
486
|
+
code: "ACTIVE_TASKS",
|
|
487
|
+
});
|
|
488
|
+
room.botIds = members;
|
|
489
|
+
}
|
|
490
|
+
if (operation === "delete") {
|
|
491
|
+
if (draft.tasks.some((t) => t.roomId === room.id && !isTerminal(t.status)))
|
|
492
|
+
throw Object.assign(new Error("Stop active tasks before deleting room"), {
|
|
493
|
+
status: 409,
|
|
494
|
+
code: "ACTIVE_TASKS",
|
|
495
|
+
});
|
|
496
|
+
draft.rooms = draft.rooms.filter((r) => r.id !== room.id);
|
|
497
|
+
draft.messages = draft.messages.filter((m) => m.roomId !== room.id);
|
|
498
|
+
draft.tasks = draft.tasks.filter((t) => t.roomId !== room.id);
|
|
499
|
+
draft.receipts = draft.receipts.filter((r) => r.roomId !== room.id);
|
|
500
|
+
return { deleted: true };
|
|
501
|
+
}
|
|
502
|
+
return { room };
|
|
503
|
+
});
|
|
504
|
+
res.json(result);
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
app.post("/api/rooms/:id/messages", async (req, res) => {
|
|
508
|
+
const owner = account(req);
|
|
509
|
+
const content = text(req.body?.text);
|
|
510
|
+
const targets = ids(req.body?.targetBotIds ?? []);
|
|
511
|
+
const transfer = handoff(req.body?.handoff);
|
|
512
|
+
const parentTaskId = req.body?.parentTaskId === undefined ? undefined : text(req.body.parentTaskId, 128);
|
|
513
|
+
const key = req.body?.idempotencyKey === undefined ? randomUUID() : text(req.body.idempotencyKey, 128);
|
|
514
|
+
const fingerprint = hashSecret(JSON.stringify({
|
|
515
|
+
content,
|
|
516
|
+
targets,
|
|
517
|
+
transfer,
|
|
518
|
+
parentTaskId,
|
|
519
|
+
sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
|
|
520
|
+
sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
|
|
521
|
+
senderType: agents.has(req) ? "bot" : "human",
|
|
522
|
+
}));
|
|
523
|
+
const result = await store.transact((draft) => {
|
|
524
|
+
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
525
|
+
if (!room)
|
|
526
|
+
fail(404, "Room missing");
|
|
527
|
+
const source = ownBot(req, draft);
|
|
528
|
+
const userSource = users.get(req)?.device;
|
|
529
|
+
if (source && !room.botIds.includes(source.id))
|
|
530
|
+
fail(403, "Source Bot is not a room member");
|
|
531
|
+
if (targets.some((id) => !room.botIds.includes(id) || !validBot(draft, id, owner.id)))
|
|
532
|
+
fail(400, "Invalid target Bot");
|
|
533
|
+
const receipt = draft.receipts.find((r) => r.roomId === room.id && r.accountId === owner.id && r.key === key);
|
|
534
|
+
if (receipt) {
|
|
535
|
+
if (receipt.fingerprint !== fingerprint)
|
|
536
|
+
fail(409, "Idempotency key reused");
|
|
537
|
+
return {
|
|
538
|
+
message: draft.messages.find((m) => m.id === receipt.messageId),
|
|
539
|
+
tasks: draft.tasks.filter((t) => draft.messages.find((m) => m.id === receipt.messageId)?.taskIds.includes(t.id)),
|
|
540
|
+
duplicate: true,
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
if (parentTaskId &&
|
|
544
|
+
!draft.tasks.some((t) => t.id === parentTaskId &&
|
|
545
|
+
t.roomId === room.id &&
|
|
546
|
+
t.accountId === owner.id &&
|
|
547
|
+
(isTerminal(t.status) || (source?.id === t.botId && t.status === "running"))))
|
|
548
|
+
fail(400, "Parent task must be terminal or the source device's running task in this room");
|
|
549
|
+
const parent = parentTaskId ? draft.tasks.find((t) => t.id === parentTaskId) : undefined;
|
|
550
|
+
if (source && targets.length && (!parent || parent.botId !== source.id))
|
|
551
|
+
fail(400, "Device dispatch requires its own running or terminal parent task");
|
|
552
|
+
const root = parent ? draft.tasks.find((t) => t.id === (parent.rootTaskId ?? parent.id)) : undefined;
|
|
553
|
+
if (parent && targets.length && !root)
|
|
554
|
+
fail(409, "Dispatch root expired");
|
|
555
|
+
const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : 0;
|
|
556
|
+
if (targets.length && depth > 8)
|
|
557
|
+
fail(409, "Dispatch depth exhausted");
|
|
558
|
+
if (targets.length && (root?.dispatchCount ?? 0) + targets.length > 16)
|
|
559
|
+
fail(409, "Dispatch budget exhausted");
|
|
560
|
+
if (root && targets.length)
|
|
561
|
+
root.dispatchCount = (root.dispatchCount ?? 0) + targets.length;
|
|
562
|
+
if (draft.tasks.filter((t) => t.roomId === room.id && !isTerminal(t.status)).length + targets.length > HISTORY)
|
|
563
|
+
fail(409, "Too many active tasks");
|
|
564
|
+
const now = Date.now();
|
|
565
|
+
const rootId = root?.id ?? randomUUID();
|
|
566
|
+
const tasks = targets.map((botId, index) => ({
|
|
567
|
+
id: !root && index === 0 ? rootId : randomUUID(),
|
|
568
|
+
rootTaskId: rootId,
|
|
569
|
+
dispatchDepth: depth,
|
|
570
|
+
...(!root && index === 0 ? { dispatchCount: targets.length } : {}),
|
|
571
|
+
attemptId: randomUUID(),
|
|
572
|
+
roomId: room.id,
|
|
573
|
+
accountId: owner.id,
|
|
574
|
+
botId,
|
|
575
|
+
deviceId: validBot(draft, botId, owner.id).deviceId,
|
|
576
|
+
botRevision: validBot(draft, botId, owner.id).revision,
|
|
577
|
+
...(source ? { sourceBotId: source.id } : {}),
|
|
578
|
+
text: content,
|
|
579
|
+
status: "queued",
|
|
580
|
+
createdAt: now,
|
|
581
|
+
updatedAt: now,
|
|
582
|
+
...(transfer ? { handoff: transfer } : {}),
|
|
583
|
+
...(parentTaskId ? { parentTaskId } : {}),
|
|
584
|
+
}));
|
|
585
|
+
const message = {
|
|
586
|
+
id: randomUUID(),
|
|
587
|
+
roomId: room.id,
|
|
588
|
+
accountId: owner.id,
|
|
589
|
+
text: content,
|
|
590
|
+
sender: source
|
|
591
|
+
? { type: "bot", id: source.id, name: source.name, sourceDeviceId: source.deviceId }
|
|
592
|
+
: {
|
|
593
|
+
type: "human",
|
|
594
|
+
id: owner.id,
|
|
595
|
+
name: userSource ? `${owner.username} · ${userSource.name}` : owner.username,
|
|
596
|
+
...(userSource ? { sourceDeviceId: userSource.id } : {}),
|
|
597
|
+
},
|
|
598
|
+
createdAt: now,
|
|
599
|
+
taskIds: tasks.map((t) => t.id),
|
|
600
|
+
targetBotIds: targets,
|
|
601
|
+
};
|
|
602
|
+
draft.tasks.push(...tasks);
|
|
603
|
+
draft.messages.push(message);
|
|
604
|
+
draft.receipts.push({ accountId: owner.id, roomId: room.id, key, fingerprint, messageId: message.id });
|
|
605
|
+
const oldMessages = draft.messages.filter((m) => m.roomId === room.id).slice(0, -HISTORY);
|
|
606
|
+
const removed = new Set(oldMessages.map((m) => m.id));
|
|
607
|
+
draft.messages = draft.messages.filter((m) => !removed.has(m.id));
|
|
608
|
+
draft.receipts = draft.receipts.filter((r) => !removed.has(r.messageId));
|
|
609
|
+
const oldTasks = new Set(draft.tasks
|
|
610
|
+
.filter((t) => t.roomId === room.id && isTerminal(t.status))
|
|
611
|
+
.slice(0, -HISTORY)
|
|
612
|
+
.map((t) => t.id));
|
|
613
|
+
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
614
|
+
return { message, tasks, duplicate: false };
|
|
615
|
+
});
|
|
616
|
+
if (!result.duplicate) {
|
|
617
|
+
for (const task of result.tasks) {
|
|
618
|
+
const deliver = options.onTask ?? options.relay?.onTask;
|
|
619
|
+
try {
|
|
620
|
+
const latest = store.snapshot();
|
|
621
|
+
if (validBot(latest, task.botId, task.accountId)?.revision !== task.botRevision ||
|
|
622
|
+
!latest.rooms.some((r) => r.id === task.roomId && r.botIds.includes(task.botId)))
|
|
623
|
+
throw new Error("Bot no longer available");
|
|
624
|
+
if (!deliver || (await deliver(task.deviceId, task)) === false)
|
|
625
|
+
throw new Error("Delivery rejected");
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
await store.transact((draft) => {
|
|
629
|
+
const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
630
|
+
if (!current || isTerminal(current.status))
|
|
631
|
+
return;
|
|
632
|
+
const report = "Task delivery failed; submit a new request to retry.";
|
|
633
|
+
current.status = "failed";
|
|
634
|
+
current.updatedAt = Date.now();
|
|
635
|
+
current.report = report;
|
|
636
|
+
draft.messages.push({
|
|
637
|
+
id: randomUUID(),
|
|
638
|
+
roomId: current.roomId,
|
|
639
|
+
accountId: current.accountId,
|
|
640
|
+
text: report,
|
|
641
|
+
sender: {
|
|
642
|
+
type: "bot",
|
|
643
|
+
id: current.botId,
|
|
644
|
+
name: draft.bots.find((bot) => bot.id === current.botId)?.name ?? current.botId,
|
|
645
|
+
sourceDeviceId: current.deviceId,
|
|
646
|
+
},
|
|
647
|
+
createdAt: current.updatedAt,
|
|
648
|
+
taskIds: [current.id],
|
|
649
|
+
});
|
|
650
|
+
const remove = new Set(draft.messages
|
|
651
|
+
.filter((message) => message.roomId === current.roomId)
|
|
652
|
+
.slice(0, -HISTORY)
|
|
653
|
+
.map((message) => message.id));
|
|
654
|
+
draft.messages = draft.messages.filter((message) => !remove.has(message.id));
|
|
655
|
+
draft.receipts = draft.receipts.filter((receipt) => !remove.has(receipt.messageId));
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const state = store.snapshot();
|
|
661
|
+
res.json({
|
|
662
|
+
message: result.message,
|
|
663
|
+
tasks: result.tasks.map((task) => state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task),
|
|
664
|
+
});
|
|
665
|
+
});
|
|
666
|
+
for (const action of ["alias", "portal"])
|
|
667
|
+
app.post(`/api/devices/:id/${action}`, async (req, res) => {
|
|
668
|
+
const owner = account(req);
|
|
669
|
+
const id = String(req.params.id);
|
|
670
|
+
if (store.getDeviceOwner(id) !== owner.id)
|
|
671
|
+
fail(404, "Device missing");
|
|
672
|
+
if (!options.portals)
|
|
673
|
+
fail(409, "Device portals unavailable");
|
|
674
|
+
if (action === "alias" && typeof req.body?.alias !== "string")
|
|
675
|
+
fail(400, "Invalid alias");
|
|
676
|
+
await options.portals.assign(id, owner.id, action === "alias" ? req.body.alias : undefined);
|
|
677
|
+
res.json({ device: visibleDevice(store.getDevice(id)) });
|
|
678
|
+
});
|
|
679
|
+
app.get("/device/:id", async (req, res) => {
|
|
680
|
+
const owner = getAccount(req);
|
|
681
|
+
res.setHeader("Cache-Control", "no-store");
|
|
682
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
683
|
+
if (!owner) {
|
|
684
|
+
res
|
|
685
|
+
.status(401)
|
|
686
|
+
.type("html")
|
|
687
|
+
.send('<!doctype html><meta charset="utf-8"><p>请先登录设备中心,再打开设备链接。</p><a href="/">Sign in / 登录设备中心</a>');
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
const id = String(req.params.id);
|
|
691
|
+
if (store.getDeviceOwner(id) !== owner.id)
|
|
692
|
+
fail(404, "Device missing");
|
|
693
|
+
if (!options.portals && !options.pathAccess)
|
|
694
|
+
fail(409, "Device portals unavailable");
|
|
695
|
+
if (!options.relay?.handleAliasOpen)
|
|
696
|
+
fail(503, "Relay unavailable");
|
|
697
|
+
if (!options.pathAccess)
|
|
698
|
+
await options.portals.assign(id, owner.id);
|
|
699
|
+
await options.relay.handleAliasOpen(req, res, id);
|
|
700
|
+
});
|
|
701
|
+
app.get("/:alias", async (req, res, next) => {
|
|
702
|
+
const entry = options.portals?.resolveAlias(String(req.params.alias));
|
|
703
|
+
if (!entry)
|
|
704
|
+
return next();
|
|
705
|
+
const owner = getAccount(req);
|
|
706
|
+
res.setHeader("Cache-Control", "no-store");
|
|
707
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
708
|
+
if (!owner) {
|
|
709
|
+
res
|
|
710
|
+
.status(401)
|
|
711
|
+
.type("html")
|
|
712
|
+
.send('<!doctype html><meta charset="utf-8"><p>Sign in to the device hub, then open this address again.</p><a href="/">Sign in / 登录设备中心</a>');
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (owner.id !== entry.accountId || store.getDeviceOwner(entry.deviceId) !== owner.id)
|
|
716
|
+
fail(404, "Device missing");
|
|
717
|
+
if (!options.relay?.handleAliasOpen)
|
|
718
|
+
fail(503, "Relay unavailable");
|
|
719
|
+
await options.relay.handleAliasOpen(req, res, entry.deviceId);
|
|
720
|
+
});
|
|
721
|
+
app.post("/api/devices/:id/open", async (req, res) => {
|
|
722
|
+
const owner = account(req);
|
|
723
|
+
const id = String(req.params.id);
|
|
724
|
+
if (store.getDeviceOwner(id) !== owner.id)
|
|
725
|
+
fail(404, "Device missing");
|
|
726
|
+
if (options.portals && !options.deviceDomain && !options.pathAccess) {
|
|
727
|
+
try {
|
|
728
|
+
await options.portals.assign(id, owner.id);
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
if (error.status !== 409)
|
|
732
|
+
throw error;
|
|
733
|
+
return res
|
|
734
|
+
.status(409)
|
|
735
|
+
.json({ code: "DEVICE_WEB_ORIGIN_REQUIRED", error: "No device portal port is available" });
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (users.has(req))
|
|
739
|
+
req.headers.origin = origin.origin;
|
|
740
|
+
if (!options.relay?.handleOpen)
|
|
741
|
+
fail(503, "Relay unavailable");
|
|
742
|
+
await options.relay.handleOpen(req, res, String(req.params.id));
|
|
743
|
+
});
|
|
744
|
+
// No catch-all: the runner mounts the UI after creation.
|
|
745
|
+
app.use((error, _req, res, _next) => {
|
|
746
|
+
res.status(error.status ?? 500).json({
|
|
747
|
+
error: error.status && error.status < 500 ? error.message : "Storage or internal error",
|
|
748
|
+
...(error.code === "ACTIVE_TASKS" ? { code: "ACTIVE_TASKS" } : {}),
|
|
749
|
+
});
|
|
750
|
+
});
|
|
751
|
+
const server = createServer((req, res) => {
|
|
752
|
+
if (options.relay?.handleRequest?.(req, res))
|
|
753
|
+
return;
|
|
754
|
+
app(req, res);
|
|
755
|
+
});
|
|
756
|
+
async function acceptTaskEvent(deviceId, event) {
|
|
757
|
+
if (!event ||
|
|
758
|
+
typeof event.taskId !== "string" ||
|
|
759
|
+
typeof event.attemptId !== "string" ||
|
|
760
|
+
typeof event.botId !== "string" ||
|
|
761
|
+
!["running", "completed", "failed", "interrupted"].includes(event.status))
|
|
762
|
+
fail(400, "Invalid task event");
|
|
763
|
+
const report = event.report === undefined ? undefined : text(event.report);
|
|
764
|
+
if (event.status === "completed" && !report)
|
|
765
|
+
fail(400, "Completed task requires agent report");
|
|
766
|
+
return store.transact((draft) => {
|
|
767
|
+
const device = draft.devices.find((d) => d.id === deviceId);
|
|
768
|
+
const task = draft.tasks.find((t) => t.id === event.taskId &&
|
|
769
|
+
t.deviceId === deviceId &&
|
|
770
|
+
t.botId === event.botId &&
|
|
771
|
+
t.attemptId === event.attemptId &&
|
|
772
|
+
t.accountId === device?.accountId);
|
|
773
|
+
const bot = draft.bots.find((b) => b.id === event.botId && b.deviceId === deviceId && b.accountId === device?.accountId);
|
|
774
|
+
if (!task || !device || !bot || !draft.rooms.some((r) => r.id === task.roomId && r.botIds.includes(bot.id)))
|
|
775
|
+
fail(404, "Task missing");
|
|
776
|
+
if (event.status !== "interrupted" && (!bot.enabled || bot.revision !== task.botRevision))
|
|
777
|
+
fail(409, "Bot configuration changed");
|
|
778
|
+
if (task.status === event.status) {
|
|
779
|
+
if (task.report !== report)
|
|
780
|
+
fail(409, "Conflicting duplicate event");
|
|
781
|
+
return task;
|
|
782
|
+
}
|
|
783
|
+
if (isTerminal(task.status) ||
|
|
784
|
+
(task.status === "queued" && event.status !== "running" && event.status !== "interrupted") ||
|
|
785
|
+
(task.status === "running" && !isTerminal(event.status)))
|
|
786
|
+
fail(409, "Invalid task transition");
|
|
787
|
+
task.status = event.status;
|
|
788
|
+
task.updatedAt = Date.now();
|
|
789
|
+
if (report)
|
|
790
|
+
task.report = report;
|
|
791
|
+
if (report) {
|
|
792
|
+
draft.messages.push({
|
|
793
|
+
id: randomUUID(),
|
|
794
|
+
roomId: task.roomId,
|
|
795
|
+
accountId: task.accountId,
|
|
796
|
+
text: report,
|
|
797
|
+
sender: { type: "bot", id: bot.id, name: bot.name, sourceDeviceId: deviceId },
|
|
798
|
+
createdAt: Date.now(),
|
|
799
|
+
taskIds: [task.id],
|
|
800
|
+
});
|
|
801
|
+
const remove = new Set(draft.messages
|
|
802
|
+
.filter((m) => m.roomId === task.roomId)
|
|
803
|
+
.slice(0, -HISTORY)
|
|
804
|
+
.map((m) => m.id));
|
|
805
|
+
draft.messages = draft.messages.filter((m) => !remove.has(m.id));
|
|
806
|
+
draft.receipts = draft.receipts.filter((r) => !remove.has(r.messageId));
|
|
807
|
+
}
|
|
808
|
+
return task;
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
return {
|
|
812
|
+
app,
|
|
813
|
+
server,
|
|
814
|
+
store,
|
|
815
|
+
getAccount,
|
|
816
|
+
getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req),
|
|
817
|
+
authenticateAgent,
|
|
818
|
+
acceptTaskEvent,
|
|
819
|
+
setRelay(relay) {
|
|
820
|
+
options.relay = relay;
|
|
821
|
+
},
|
|
822
|
+
async close() {
|
|
823
|
+
pairs.clear();
|
|
824
|
+
if (server.listening)
|
|
825
|
+
await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
|
826
|
+
await store.close();
|
|
827
|
+
},
|
|
828
|
+
};
|
|
829
|
+
}
|