@clagentic/console 1.0.0-beta.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/CREDITS.md +3 -0
- package/LICENSE +21 -0
- package/README.md +250 -0
- package/bin/cli.js +2812 -0
- package/lib/agents-favorites.js +164 -0
- package/lib/agents.js +282 -0
- package/lib/ask-user-mcp-server.js +120 -0
- package/lib/browser-mcp-server.js +484 -0
- package/lib/build-user-env.js +63 -0
- package/lib/certs/fullchain.pem +47 -0
- package/lib/certs/privkey.pem +5 -0
- package/lib/cli-sessions.js +265 -0
- package/lib/codex-defaults.js +18 -0
- package/lib/config.js +332 -0
- package/lib/crisis-safety.js +60 -0
- package/lib/daemon-projects.js +164 -0
- package/lib/daemon.js +1602 -0
- package/lib/dm.js +128 -0
- package/lib/ipc.js +125 -0
- package/lib/ipv4-only.js +39 -0
- package/lib/mcp-local.js +385 -0
- package/lib/notes.js +141 -0
- package/lib/os-users.js +529 -0
- package/lib/pages.js +1325 -0
- package/lib/project-connection.js +302 -0
- package/lib/project-external-trigger.js +236 -0
- package/lib/project-file-watch.js +120 -0
- package/lib/project-filesystem.js +528 -0
- package/lib/project-http.js +753 -0
- package/lib/project-image.js +95 -0
- package/lib/project-knowledge.js +88 -0
- package/lib/project-loop.js +1304 -0
- package/lib/project-mcp.js +374 -0
- package/lib/project-memory.js +39 -0
- package/lib/project-notifications.js +262 -0
- package/lib/project-sessions.js +1581 -0
- package/lib/project-user-mention.js +193 -0
- package/lib/project-user-message.js +628 -0
- package/lib/project.js +1303 -0
- package/lib/public/app.js +1031 -0
- package/lib/public/apple-touch-icon.png +0 -0
- package/lib/public/claude-code-avatar.png +0 -0
- package/lib/public/codex-avatar.png +0 -0
- package/lib/public/console-icon.png +0 -0
- package/lib/public/css/admin.css +736 -0
- package/lib/public/css/agent-picker.css +119 -0
- package/lib/public/css/base.css +235 -0
- package/lib/public/css/channel-layout.css +441 -0
- package/lib/public/css/command-palette.css +559 -0
- package/lib/public/css/debate.css +1609 -0
- package/lib/public/css/diff.css +139 -0
- package/lib/public/css/filebrowser.css +1976 -0
- package/lib/public/css/highlight.css +144 -0
- package/lib/public/css/home-hub.css +545 -0
- package/lib/public/css/icon-strip.css +1856 -0
- package/lib/public/css/input.css +1349 -0
- package/lib/public/css/loop.css +1248 -0
- package/lib/public/css/mention.css +317 -0
- package/lib/public/css/menus.css +857 -0
- package/lib/public/css/messages.css +1833 -0
- package/lib/public/css/mobile-nav.css +1332 -0
- package/lib/public/css/notifications-center.css +296 -0
- package/lib/public/css/overlays.css +1273 -0
- package/lib/public/css/playbook.css +264 -0
- package/lib/public/css/profile.css +397 -0
- package/lib/public/css/rewind.css +671 -0
- package/lib/public/css/scheduler-modal.css +1495 -0
- package/lib/public/css/scheduler.css +1420 -0
- package/lib/public/css/server-settings.css +909 -0
- package/lib/public/css/session-search.css +159 -0
- package/lib/public/css/sidebar.css +2012 -0
- package/lib/public/css/skills.css +789 -0
- package/lib/public/css/sticky-notes.css +854 -0
- package/lib/public/css/stt.css +155 -0
- package/lib/public/css/title-bar.css +674 -0
- package/lib/public/css/tooltip.css +67 -0
- package/lib/public/css/user-settings.css +702 -0
- package/lib/public/emoji-data.json +1 -0
- package/lib/public/favicon-banded-32.png +0 -0
- package/lib/public/favicon-banded.png +0 -0
- package/lib/public/favicon-dark.svg +32 -0
- package/lib/public/favicon.svg +32 -0
- package/lib/public/icon-192.png +0 -0
- package/lib/public/icon-512.png +0 -0
- package/lib/public/icon-banded-76.png +0 -0
- package/lib/public/icon-banded-96.png +0 -0
- package/lib/public/icon-mono.svg +25 -0
- package/lib/public/icons/email/gmail.svg +7 -0
- package/lib/public/icons/email/outlook.svg +35 -0
- package/lib/public/icons/email/yahoo.svg +1 -0
- package/lib/public/index.html +1946 -0
- package/lib/public/manifest.json +27 -0
- package/lib/public/markdown-worker.js +43 -0
- package/lib/public/marked.min.js +6 -0
- package/lib/public/modules/admin.js +954 -0
- package/lib/public/modules/agent-picker.js +429 -0
- package/lib/public/modules/app-connection.js +216 -0
- package/lib/public/modules/app-cursors.js +492 -0
- package/lib/public/modules/app-dm.js +265 -0
- package/lib/public/modules/app-favicon.js +231 -0
- package/lib/public/modules/app-header.js +242 -0
- package/lib/public/modules/app-home-hub.js +432 -0
- package/lib/public/modules/app-loop-ui.js +691 -0
- package/lib/public/modules/app-loop-wizard.js +439 -0
- package/lib/public/modules/app-messages.js +1415 -0
- package/lib/public/modules/app-misc.js +463 -0
- package/lib/public/modules/app-notifications.js +651 -0
- package/lib/public/modules/app-panels.js +1061 -0
- package/lib/public/modules/app-projects.js +875 -0
- package/lib/public/modules/app-rate-limit.js +529 -0
- package/lib/public/modules/app-rendering.js +739 -0
- package/lib/public/modules/app-skills-install.js +285 -0
- package/lib/public/modules/avatar.js +36 -0
- package/lib/public/modules/command-palette.js +491 -0
- package/lib/public/modules/console-logo.js +162 -0
- package/lib/public/modules/context-sources.js +365 -0
- package/lib/public/modules/diff.js +412 -0
- package/lib/public/modules/dom-refs.js +21 -0
- package/lib/public/modules/emoji-picker.js +222 -0
- package/lib/public/modules/events.js +21 -0
- package/lib/public/modules/filebrowser.js +1966 -0
- package/lib/public/modules/fileicons.js +172 -0
- package/lib/public/modules/icons.js +80 -0
- package/lib/public/modules/input.js +1102 -0
- package/lib/public/modules/longpress.js +74 -0
- package/lib/public/modules/markdown.js +486 -0
- package/lib/public/modules/mcp-ui.js +295 -0
- package/lib/public/modules/mention.js +1093 -0
- package/lib/public/modules/notifications.js +613 -0
- package/lib/public/modules/playbook.js +578 -0
- package/lib/public/modules/profile.js +594 -0
- package/lib/public/modules/project-settings.js +849 -0
- package/lib/public/modules/project-switcher.js +375 -0
- package/lib/public/modules/qrcode.js +87 -0
- package/lib/public/modules/rewind.js +381 -0
- package/lib/public/modules/scheduler-config.js +1611 -0
- package/lib/public/modules/scheduler-history.js +131 -0
- package/lib/public/modules/scheduler.js +1689 -0
- package/lib/public/modules/server-settings.js +842 -0
- package/lib/public/modules/session-search.js +456 -0
- package/lib/public/modules/settings-defaults.js +253 -0
- package/lib/public/modules/sidebar-mobile.js +1425 -0
- package/lib/public/modules/sidebar-projects.js +2022 -0
- package/lib/public/modules/sidebar-sessions.js +1548 -0
- package/lib/public/modules/sidebar-users.js +449 -0
- package/lib/public/modules/sidebar.js +348 -0
- package/lib/public/modules/skills.js +793 -0
- package/lib/public/modules/state.js +3 -0
- package/lib/public/modules/sticky-notes.js +1221 -0
- package/lib/public/modules/store.js +34 -0
- package/lib/public/modules/stt.js +266 -0
- package/lib/public/modules/terminal.js +987 -0
- package/lib/public/modules/theme.js +812 -0
- package/lib/public/modules/tool-palette.js +562 -0
- package/lib/public/modules/tools.js +2285 -0
- package/lib/public/modules/tooltip.js +150 -0
- package/lib/public/modules/user-settings.js +544 -0
- package/lib/public/modules/utils.js +56 -0
- package/lib/public/modules/ws-ref.js +26 -0
- package/lib/public/style.css +34 -0
- package/lib/public/sw.js +159 -0
- package/lib/push.js +149 -0
- package/lib/scheduler.js +471 -0
- package/lib/sdk-bridge.js +1792 -0
- package/lib/sdk-message-processor.js +740 -0
- package/lib/sdk-message-queue.js +42 -0
- package/lib/sdk-skill-discovery.js +131 -0
- package/lib/sdk-worker.js +677 -0
- package/lib/server-admin.js +712 -0
- package/lib/server-auth.js +737 -0
- package/lib/server-dm.js +170 -0
- package/lib/server-palette.js +104 -0
- package/lib/server-settings.js +553 -0
- package/lib/server-skills.js +280 -0
- package/lib/server.js +1390 -0
- package/lib/session-search.js +693 -0
- package/lib/sessions.js +946 -0
- package/lib/smtp.js +221 -0
- package/lib/terminal-manager.js +219 -0
- package/lib/terminal.js +39 -0
- package/lib/themes/ayu-light.json +9 -0
- package/lib/themes/catppuccin-latte.json +9 -0
- package/lib/themes/catppuccin-mocha.json +9 -0
- package/lib/themes/clagentic-dark.json +10 -0
- package/lib/themes/clagentic-light.json +10 -0
- package/lib/themes/dracula.json +9 -0
- package/lib/themes/everforest-light.json +9 -0
- package/lib/themes/everforest.json +9 -0
- package/lib/themes/github-light.json +9 -0
- package/lib/themes/gruvbox-dark.json +9 -0
- package/lib/themes/gruvbox-light.json +9 -0
- package/lib/themes/monokai.json +9 -0
- package/lib/themes/nord-light.json +9 -0
- package/lib/themes/nord.json +9 -0
- package/lib/themes/one-dark.json +9 -0
- package/lib/themes/one-light.json +9 -0
- package/lib/themes/rose-pine-dawn.json +9 -0
- package/lib/themes/rose-pine.json +9 -0
- package/lib/themes/solarized-dark.json +9 -0
- package/lib/themes/solarized-light.json +9 -0
- package/lib/themes/tokyo-night-light.json +9 -0
- package/lib/themes/tokyo-night.json +9 -0
- package/lib/updater.js +124 -0
- package/lib/user-presence.js +92 -0
- package/lib/users-auth.js +146 -0
- package/lib/users-permissions.js +118 -0
- package/lib/users-preferences.js +254 -0
- package/lib/users.js +465 -0
- package/lib/utils.js +64 -0
- package/lib/worktree.js +134 -0
- package/lib/ws-schema.js +464 -0
- package/lib/yoke/adapters/claude-worker.js +759 -0
- package/lib/yoke/adapters/claude.js +1599 -0
- package/lib/yoke/adapters/codex.js +1559 -0
- package/lib/yoke/codex-app-server.js +352 -0
- package/lib/yoke/index.js +319 -0
- package/lib/yoke/instructions.js +61 -0
- package/lib/yoke/interface.js +98 -0
- package/lib/yoke/mcp-bridge-server.js +302 -0
- package/lib/yoke/package.json +7 -0
- package/package.json +72 -0
package/lib/server.js
ADDED
|
@@ -0,0 +1,1390 @@
|
|
|
1
|
+
var http = require("http");
|
|
2
|
+
var fs = require("fs");
|
|
3
|
+
var path = require("path");
|
|
4
|
+
var { WebSocketServer } = require("ws");
|
|
5
|
+
var pages = require("./pages");
|
|
6
|
+
var smtp = require("./smtp");
|
|
7
|
+
var { createProjectContext } = require("./project");
|
|
8
|
+
var users = require("./users");
|
|
9
|
+
var dm = require("./dm");
|
|
10
|
+
var serverAuth = require("./server-auth");
|
|
11
|
+
var serverSkills = require("./server-skills");
|
|
12
|
+
var serverDm = require("./server-dm");
|
|
13
|
+
var serverAdmin = require("./server-admin");
|
|
14
|
+
var serverSettings = require("./server-settings");
|
|
15
|
+
var serverPalette = require("./server-palette");
|
|
16
|
+
|
|
17
|
+
var { CONFIG_DIR } = require("./config");
|
|
18
|
+
var { provisionLinuxUser } = require("./os-users");
|
|
19
|
+
|
|
20
|
+
var https = require("https");
|
|
21
|
+
var pkg = require("../package.json");
|
|
22
|
+
|
|
23
|
+
var publicDir = path.join(__dirname, "public");
|
|
24
|
+
var bundledThemesDir = path.join(__dirname, "themes");
|
|
25
|
+
var userThemesDir = path.join(CONFIG_DIR, "themes");
|
|
26
|
+
|
|
27
|
+
// --- HTTP helpers (used by skills proxy and extension download) ---
|
|
28
|
+
|
|
29
|
+
function httpGetBinary(url) {
|
|
30
|
+
return new Promise(function (resolve, reject) {
|
|
31
|
+
var mod = url.startsWith("https") ? https : http;
|
|
32
|
+
mod.get(url, { headers: { "User-Agent": "Clay/1.0" } }, function (resp) {
|
|
33
|
+
if (resp.statusCode >= 300 && resp.statusCode < 400 && resp.headers.location) {
|
|
34
|
+
return httpGetBinary(resp.headers.location).then(resolve, reject);
|
|
35
|
+
}
|
|
36
|
+
if (resp.statusCode !== 200) {
|
|
37
|
+
return reject(new Error("HTTP " + resp.statusCode));
|
|
38
|
+
}
|
|
39
|
+
var chunks = [];
|
|
40
|
+
resp.on("data", function (c) { chunks.push(c); });
|
|
41
|
+
resp.on("end", function () { resolve(Buffer.concat(chunks)); });
|
|
42
|
+
resp.on("error", reject);
|
|
43
|
+
}).on("error", reject);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
var MIME_TYPES = {
|
|
49
|
+
".html": "text/html",
|
|
50
|
+
".css": "text/css",
|
|
51
|
+
".js": "application/javascript",
|
|
52
|
+
".json": "application/json",
|
|
53
|
+
".png": "image/png",
|
|
54
|
+
".jpg": "image/jpeg",
|
|
55
|
+
".jpeg": "image/jpeg",
|
|
56
|
+
".gif": "image/gif",
|
|
57
|
+
".webp": "image/webp",
|
|
58
|
+
".bmp": "image/bmp",
|
|
59
|
+
".svg": "image/svg+xml",
|
|
60
|
+
".ico": "image/x-icon",
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
var generateAuthToken = serverAuth.generateAuthToken;
|
|
64
|
+
var verifyPin = serverAuth.verifyPin;
|
|
65
|
+
|
|
66
|
+
function serveStatic(urlPath, res) {
|
|
67
|
+
if (urlPath === "/") urlPath = "/index.html";
|
|
68
|
+
|
|
69
|
+
var filePath = path.join(publicDir, urlPath);
|
|
70
|
+
|
|
71
|
+
if (!filePath.startsWith(publicDir)) {
|
|
72
|
+
res.writeHead(403);
|
|
73
|
+
res.end("Forbidden");
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
try {
|
|
78
|
+
var content = fs.readFileSync(filePath);
|
|
79
|
+
var ext = path.extname(filePath);
|
|
80
|
+
var mime = MIME_TYPES[ext] || "application/octet-stream";
|
|
81
|
+
var isImage = ext === ".png" || ext === ".jpg" || ext === ".jpeg" || ext === ".gif" || ext === ".svg" || ext === ".webp" || ext === ".ico";
|
|
82
|
+
var cacheControl = isImage ? "public, max-age=86400, immutable" : "no-cache";
|
|
83
|
+
res.writeHead(200, {
|
|
84
|
+
"Content-Type": mime + (isImage ? "" : "; charset=utf-8"),
|
|
85
|
+
"Cache-Control": cacheControl,
|
|
86
|
+
});
|
|
87
|
+
res.end(content);
|
|
88
|
+
return true;
|
|
89
|
+
} catch (e) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Extract slug from URL path: /p/{slug}/... → slug
|
|
96
|
+
* Returns null if path doesn't match /p/{slug}
|
|
97
|
+
*/
|
|
98
|
+
function extractSlug(urlPath) {
|
|
99
|
+
var match = urlPath.match(/^\/p\/([a-z0-9_-]+)(\/|$)/);
|
|
100
|
+
return match ? match[1] : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Strip the /p/{slug} prefix from URL path
|
|
105
|
+
*/
|
|
106
|
+
function stripPrefix(urlPath, slug) {
|
|
107
|
+
var prefix = "/p/" + slug;
|
|
108
|
+
var rest = urlPath.substring(prefix.length);
|
|
109
|
+
return rest || "/";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Create a multi-project server.
|
|
114
|
+
* opts: { tlsOptions, caPath, pinHash, port, debug, dangerouslySkipPermissions }
|
|
115
|
+
*/
|
|
116
|
+
function createServer(opts) {
|
|
117
|
+
var tlsOptions = opts.tlsOptions || null;
|
|
118
|
+
var caPath = opts.caPath || null;
|
|
119
|
+
var pinHash = opts.pinHash || null;
|
|
120
|
+
var portNum = opts.port || 2633;
|
|
121
|
+
var debug = opts.debug || false;
|
|
122
|
+
var dangerouslySkipPermissions = opts.dangerouslySkipPermissions || false;
|
|
123
|
+
var osUsers = opts.osUsers || false;
|
|
124
|
+
var lanHost = opts.lanHost || null;
|
|
125
|
+
var onAddProject = opts.onAddProject || null;
|
|
126
|
+
var onCreateProject = opts.onCreateProject || null;
|
|
127
|
+
var onCloneProject = opts.onCloneProject || null;
|
|
128
|
+
var onRemoveProject = opts.onRemoveProject || null;
|
|
129
|
+
var onReorderProjects = opts.onReorderProjects || null;
|
|
130
|
+
var onSetProjectTitle = opts.onSetProjectTitle || null;
|
|
131
|
+
var onSetProjectIcon = opts.onSetProjectIcon || null;
|
|
132
|
+
var onSetProjectPreferredAgent = opts.onSetProjectPreferredAgent || null;
|
|
133
|
+
var onSetProjectFolder = opts.onSetProjectFolder || null;
|
|
134
|
+
var onRenameProjectFolder = opts.onRenameProjectFolder || null;
|
|
135
|
+
var onSetFolderIcon = opts.onSetFolderIcon || null;
|
|
136
|
+
var getFolderMeta = opts.getFolderMeta || function () { return {}; };
|
|
137
|
+
var onProjectOwnerChanged = opts.onProjectOwnerChanged || null;
|
|
138
|
+
var onGetServerDefaultEffort = opts.onGetServerDefaultEffort || null;
|
|
139
|
+
var onSetServerDefaultEffort = opts.onSetServerDefaultEffort || null;
|
|
140
|
+
var onGetProjectDefaultEffort = opts.onGetProjectDefaultEffort || null;
|
|
141
|
+
var onSetProjectDefaultEffort = opts.onSetProjectDefaultEffort || null;
|
|
142
|
+
var onGetServerDefaultModel = opts.onGetServerDefaultModel || null;
|
|
143
|
+
var onSetServerDefaultModel = opts.onSetServerDefaultModel || null;
|
|
144
|
+
var onGetProjectDefaultModel = opts.onGetProjectDefaultModel || null;
|
|
145
|
+
var onSetProjectDefaultModel = opts.onSetProjectDefaultModel || null;
|
|
146
|
+
var onGetServerDefaultMode = opts.onGetServerDefaultMode || null;
|
|
147
|
+
var onSetServerDefaultMode = opts.onSetServerDefaultMode || null;
|
|
148
|
+
var onGetProjectDefaultMode = opts.onGetProjectDefaultMode || null;
|
|
149
|
+
var onSetProjectDefaultMode = opts.onSetProjectDefaultMode || null;
|
|
150
|
+
var onGetServerDefaultBetas = opts.onGetServerDefaultBetas || null;
|
|
151
|
+
var onSetServerDefaultBetas = opts.onSetServerDefaultBetas || null;
|
|
152
|
+
var onGetProjectDefaultBetas = opts.onGetProjectDefaultBetas || null;
|
|
153
|
+
var onSetProjectDefaultBetas = opts.onSetProjectDefaultBetas || null;
|
|
154
|
+
var onGetProjectMcpServers = opts.onGetProjectMcpServers || null;
|
|
155
|
+
var onSetProjectMcpServers = opts.onSetProjectMcpServers || null;
|
|
156
|
+
var onGetDaemonConfig = opts.onGetDaemonConfig || null;
|
|
157
|
+
var onSetPin = opts.onSetPin || null;
|
|
158
|
+
var onSetKeepAwake = opts.onSetKeepAwake || null;
|
|
159
|
+
var onSetImageRetention = opts.onSetImageRetention || null;
|
|
160
|
+
var onShutdown = opts.onShutdown || null;
|
|
161
|
+
var onRestart = opts.onRestart || null;
|
|
162
|
+
var onSetUpdateChannel = opts.onSetUpdateChannel || null;
|
|
163
|
+
var onUpgradePin = opts.onUpgradePin || null;
|
|
164
|
+
var onSetProjectVisibility = opts.onSetProjectVisibility || null;
|
|
165
|
+
var onSetProjectAllowedUsers = opts.onSetProjectAllowedUsers || null;
|
|
166
|
+
var onGetProjectAccess = opts.onGetProjectAccess || null;
|
|
167
|
+
var onCreateWorktree = opts.onCreateWorktree || null;
|
|
168
|
+
var onUserProvisioned = opts.onUserProvisioned || null;
|
|
169
|
+
var onUserDeleted = opts.onUserDeleted || null;
|
|
170
|
+
var getRemovedProjects = opts.getRemovedProjects || function () { return []; };
|
|
171
|
+
|
|
172
|
+
// --- Auth module ---
|
|
173
|
+
var auth = serverAuth.attachAuth({
|
|
174
|
+
users: users,
|
|
175
|
+
smtp: smtp,
|
|
176
|
+
pages: pages,
|
|
177
|
+
tlsOptions: tlsOptions,
|
|
178
|
+
osUsers: osUsers,
|
|
179
|
+
pinHash: pinHash,
|
|
180
|
+
provisionLinuxUser: provisionLinuxUser,
|
|
181
|
+
onUpgradePin: onUpgradePin,
|
|
182
|
+
onUserProvisioned: onUserProvisioned,
|
|
183
|
+
});
|
|
184
|
+
var getMultiUserFromReq = auth.getMultiUserFromReq;
|
|
185
|
+
var isRequestAuthed = auth.isRequestAuthed;
|
|
186
|
+
var parseCookies = auth.parseCookies;
|
|
187
|
+
|
|
188
|
+
var realVersion = require("../package.json").version;
|
|
189
|
+
var currentVersion = debug ? "0.0.9" : realVersion;
|
|
190
|
+
|
|
191
|
+
var caContent = caPath ? (function () { try { return fs.readFileSync(caPath); } catch (e) { return null; } })() : null;
|
|
192
|
+
|
|
193
|
+
// --- Project registry ---
|
|
194
|
+
var projects = new Map(); // slug → projectContext
|
|
195
|
+
|
|
196
|
+
// --- Admin module ---
|
|
197
|
+
var admin = serverAdmin.attachAdmin({
|
|
198
|
+
users: users,
|
|
199
|
+
smtp: smtp,
|
|
200
|
+
getMultiUserFromReq: getMultiUserFromReq,
|
|
201
|
+
projects: projects,
|
|
202
|
+
osUsers: osUsers,
|
|
203
|
+
tlsOptions: tlsOptions,
|
|
204
|
+
portNum: portNum,
|
|
205
|
+
provisionLinuxUser: provisionLinuxUser,
|
|
206
|
+
onUserProvisioned: onUserProvisioned,
|
|
207
|
+
onUserDeleted: onUserDeleted,
|
|
208
|
+
revokeUserTokens: auth.revokeUserTokens,
|
|
209
|
+
onSetProjectVisibility: onSetProjectVisibility,
|
|
210
|
+
onSetProjectAllowedUsers: onSetProjectAllowedUsers,
|
|
211
|
+
onGetProjectAccess: onGetProjectAccess,
|
|
212
|
+
onProjectOwnerChanged: onProjectOwnerChanged,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
var skills = serverSkills.attachSkills({
|
|
216
|
+
users: users,
|
|
217
|
+
osUsers: osUsers,
|
|
218
|
+
getMultiUserFromReq: getMultiUserFromReq,
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
var settings = serverSettings.attachSettings({
|
|
222
|
+
users: users,
|
|
223
|
+
getMultiUserFromReq: getMultiUserFromReq,
|
|
224
|
+
projects: projects,
|
|
225
|
+
opts: opts,
|
|
226
|
+
CONFIG_DIR: CONFIG_DIR,
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
var palette = serverPalette.attachPalette({
|
|
230
|
+
users: users,
|
|
231
|
+
projects: projects,
|
|
232
|
+
getMultiUserFromReq: getMultiUserFromReq,
|
|
233
|
+
onGetProjectAccess: onGetProjectAccess,
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// --- Push module (global) ---
|
|
237
|
+
var pushModule = null;
|
|
238
|
+
try {
|
|
239
|
+
var { initPush } = require("./push");
|
|
240
|
+
pushModule = initPush();
|
|
241
|
+
} catch (e) {}
|
|
242
|
+
|
|
243
|
+
// --- Notifications module (global singleton, shared by all projects) ---
|
|
244
|
+
var { attachNotifications: _attachNotifications } = require("./project-notifications");
|
|
245
|
+
var _globalNotifications = _attachNotifications({
|
|
246
|
+
broadcastAll: function (msg) { broadcastAll(msg); },
|
|
247
|
+
sendToUser: function (userId, msg) { sendToUser(userId, msg); },
|
|
248
|
+
pushModule: pushModule,
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
// --- External trigger watcher (global singleton) ---
|
|
252
|
+
// Watches ~/.clay/external-triggers/ for JSON files dropped by external
|
|
253
|
+
// processes. On valid file: spawns a session in the named project with
|
|
254
|
+
// initialPrompt pre-loaded as the first user-turn. No UI notification is
|
|
255
|
+
// emitted — the trigger carries its own notification channel (e.g. ntfy).
|
|
256
|
+
var { attachExternalTrigger } = require("./project-external-trigger");
|
|
257
|
+
var { EXTERNAL_TRIGGERS_DIR } = require("./config");
|
|
258
|
+
var _externalTrigger = attachExternalTrigger({
|
|
259
|
+
triggersDir: EXTERNAL_TRIGGERS_DIR,
|
|
260
|
+
getProject: function (slug) { return projects.get(slug) || null; },
|
|
261
|
+
});
|
|
262
|
+
_externalTrigger.startWatcher();
|
|
263
|
+
|
|
264
|
+
// --- Security headers ---
|
|
265
|
+
var securityHeaders = {
|
|
266
|
+
"X-Content-Type-Options": "nosniff",
|
|
267
|
+
"X-Frame-Options": "DENY",
|
|
268
|
+
"Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://esm.sh; worker-src 'self' https://cdn.jsdelivr.net blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; img-src * data: blob:; connect-src 'self' ws: wss: https://cdn.jsdelivr.net https://esm.sh https://api.dicebear.com https://api.open-meteo.com https://ipapi.co; font-src 'self' data: https://fonts.gstatic.com https://cdn.jsdelivr.net;",
|
|
269
|
+
};
|
|
270
|
+
if (tlsOptions) {
|
|
271
|
+
securityHeaders["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains";
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function setSecurityHeaders(res) {
|
|
275
|
+
var keys = Object.keys(securityHeaders);
|
|
276
|
+
for (var i = 0; i < keys.length; i++) {
|
|
277
|
+
res.setHeader(keys[i], securityHeaders[keys[i]]);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// --- HTTP handler ---
|
|
282
|
+
var appHandler = function (req, res) {
|
|
283
|
+
setSecurityHeaders(res);
|
|
284
|
+
var fullUrl = req.url.split("?")[0];
|
|
285
|
+
|
|
286
|
+
// --- Auth routes (delegated to server-auth) ---
|
|
287
|
+
if (auth.handleRequest(req, res, fullUrl)) return;
|
|
288
|
+
// CA certificate download
|
|
289
|
+
if (req.url === "/ca/download" && req.method === "GET" && caContent) {
|
|
290
|
+
res.writeHead(200, {
|
|
291
|
+
"Content-Type": "application/x-pem-file",
|
|
292
|
+
"Content-Disposition": 'attachment; filename="clagentic-ca.pem"',
|
|
293
|
+
});
|
|
294
|
+
res.end(caContent);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Chrome extension download (proxy from GitHub)
|
|
299
|
+
if (fullUrl === "/api/extension/download" && req.method === "GET") {
|
|
300
|
+
if (!isRequestAuthed(req)) {
|
|
301
|
+
res.writeHead(401, { "Content-Type": "application/json" });
|
|
302
|
+
res.end(JSON.stringify({ error: "Unauthorized" }));
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
var archiveUrl = "https://github.com/chadbyte/clay-chrome/archive/refs/heads/main.zip";
|
|
306
|
+
httpGetBinary(archiveUrl).then(function (buf) {
|
|
307
|
+
res.writeHead(200, {
|
|
308
|
+
"Content-Type": "application/zip",
|
|
309
|
+
"Content-Disposition": 'attachment; filename="clay-chrome-extension.zip"',
|
|
310
|
+
"Content-Length": buf.length,
|
|
311
|
+
});
|
|
312
|
+
res.end(buf);
|
|
313
|
+
}).catch(function (err) {
|
|
314
|
+
res.writeHead(502, { "Content-Type": "application/json" });
|
|
315
|
+
res.end(JSON.stringify({ error: "Failed to download extension: " + (err.message || "unknown error") }));
|
|
316
|
+
});
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// CORS preflight for cross-origin requests (HTTP onboarding → HTTPS)
|
|
321
|
+
if (req.method === "OPTIONS") {
|
|
322
|
+
res.writeHead(204, {
|
|
323
|
+
"Access-Control-Allow-Origin": "*",
|
|
324
|
+
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
|
325
|
+
"Access-Control-Allow-Headers": "Content-Type",
|
|
326
|
+
"Access-Control-Max-Age": "86400",
|
|
327
|
+
});
|
|
328
|
+
res.end();
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Setup page
|
|
333
|
+
if (fullUrl === "/setup" && req.method === "GET") {
|
|
334
|
+
var host = req.headers.host || "localhost";
|
|
335
|
+
var hostname = host.split(":")[0];
|
|
336
|
+
var protocol = tlsOptions ? "https" : "http";
|
|
337
|
+
var setupUrl = protocol + "://" + hostname + ":" + portNum;
|
|
338
|
+
var lanMode = /[?&]mode=lan/.test(req.url);
|
|
339
|
+
res.writeHead(200, {
|
|
340
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
341
|
+
"Access-Control-Allow-Origin": "*",
|
|
342
|
+
});
|
|
343
|
+
res.end(pages.setupPageHtml(setupUrl, setupUrl, !!caContent, lanMode));
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// PWA install guide (builtin cert mode, no CA step needed)
|
|
348
|
+
if (fullUrl === "/pwa" && req.method === "GET") {
|
|
349
|
+
var host = req.headers.host || "localhost";
|
|
350
|
+
var hostname = host.split(":")[0];
|
|
351
|
+
var protocol = tlsOptions ? "https" : "http";
|
|
352
|
+
var pwaUrl = protocol + "://" + hostname + ":" + portNum;
|
|
353
|
+
res.writeHead(200, {
|
|
354
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
355
|
+
});
|
|
356
|
+
res.end(pages.setupPageHtml(pwaUrl, pwaUrl, false, true));
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Global push endpoints (used by setup page)
|
|
361
|
+
if (req.method === "GET" && fullUrl === "/api/vapid-public-key" && pushModule) {
|
|
362
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
363
|
+
res.end(JSON.stringify({ publicKey: pushModule.publicKey }));
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (req.method === "POST" && fullUrl === "/api/push-subscribe" && pushModule) {
|
|
368
|
+
var body = "";
|
|
369
|
+
req.on("data", function (chunk) { body += chunk; });
|
|
370
|
+
req.on("end", function () {
|
|
371
|
+
try {
|
|
372
|
+
var parsed = JSON.parse(body);
|
|
373
|
+
var sub = parsed.subscription || parsed;
|
|
374
|
+
var _httpPushUser = getMultiUserFromReq(req);
|
|
375
|
+
pushModule.addSubscription(sub, parsed.replaceEndpoint, _httpPushUser ? _httpPushUser.id : null);
|
|
376
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
377
|
+
res.end('{"ok":true}');
|
|
378
|
+
} catch (e) {
|
|
379
|
+
res.writeHead(400);
|
|
380
|
+
res.end("Bad request");
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Health check endpoint
|
|
387
|
+
// Unauthenticated: minimal liveness info only
|
|
388
|
+
// Authenticated: full system details (memory, pid, version, sessions)
|
|
389
|
+
if (req.method === "GET" && fullUrl === "/api/health") {
|
|
390
|
+
var health = {
|
|
391
|
+
status: "ok",
|
|
392
|
+
timestamp: new Date().toISOString(),
|
|
393
|
+
};
|
|
394
|
+
if (isRequestAuthed(req)) {
|
|
395
|
+
var mem = process.memoryUsage();
|
|
396
|
+
var activeSessions = 0;
|
|
397
|
+
projects.forEach(function (ctx) {
|
|
398
|
+
if (ctx && ctx.clients) {
|
|
399
|
+
activeSessions += ctx.clients.size || 0;
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
health.uptime = process.uptime();
|
|
403
|
+
health.version = pkg.version;
|
|
404
|
+
health.node = process.version;
|
|
405
|
+
health.sessions = activeSessions;
|
|
406
|
+
health.projects = projects.size;
|
|
407
|
+
health.memory = {
|
|
408
|
+
rss: mem.rss,
|
|
409
|
+
heapUsed: mem.heapUsed,
|
|
410
|
+
heapTotal: mem.heapTotal,
|
|
411
|
+
};
|
|
412
|
+
health.pid = process.pid;
|
|
413
|
+
}
|
|
414
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
415
|
+
res.end(JSON.stringify(health));
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// Theme list: bundled (lib/themes/) + user (~/.clay/themes/)
|
|
420
|
+
if (req.method === "GET" && fullUrl === "/api/themes") {
|
|
421
|
+
var bundled = {};
|
|
422
|
+
var custom = {};
|
|
423
|
+
// Read bundled themes
|
|
424
|
+
try {
|
|
425
|
+
var bFiles = fs.readdirSync(bundledThemesDir);
|
|
426
|
+
for (var i = 0; i < bFiles.length; i++) {
|
|
427
|
+
if (!bFiles[i].endsWith(".json")) continue;
|
|
428
|
+
try {
|
|
429
|
+
var raw = fs.readFileSync(path.join(bundledThemesDir, bFiles[i]), "utf8");
|
|
430
|
+
var id = bFiles[i].replace(/\.json$/, "");
|
|
431
|
+
bundled[id] = JSON.parse(raw);
|
|
432
|
+
} catch (e) {}
|
|
433
|
+
}
|
|
434
|
+
} catch (e) {}
|
|
435
|
+
// Read user themes (override bundled if same id)
|
|
436
|
+
try {
|
|
437
|
+
var uFiles = fs.readdirSync(userThemesDir);
|
|
438
|
+
for (var j = 0; j < uFiles.length; j++) {
|
|
439
|
+
if (!uFiles[j].endsWith(".json")) continue;
|
|
440
|
+
try {
|
|
441
|
+
var uRaw = fs.readFileSync(path.join(userThemesDir, uFiles[j]), "utf8");
|
|
442
|
+
var uid = uFiles[j].replace(/\.json$/, "");
|
|
443
|
+
custom[uid] = JSON.parse(uRaw);
|
|
444
|
+
} catch (e) {}
|
|
445
|
+
}
|
|
446
|
+
} catch (e) {}
|
|
447
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
448
|
+
res.end(JSON.stringify({ bundled: bundled, custom: custom }));
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (settings.handleRequest(req, res, fullUrl)) return;
|
|
453
|
+
|
|
454
|
+
// --- Admin API endpoints (multi-user mode only) ---
|
|
455
|
+
if (admin.handleRequest(req, res, fullUrl)) return;
|
|
456
|
+
|
|
457
|
+
// --- Palette search (delegated to server-palette) ---
|
|
458
|
+
if (palette.handleRequest(req, res, fullUrl)) return;
|
|
459
|
+
|
|
460
|
+
// Multi-user info endpoint (who am I?)
|
|
461
|
+
if (req.method === "GET" && fullUrl === "/api/me") {
|
|
462
|
+
if (!users.isMultiUser()) {
|
|
463
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
464
|
+
res.end('{"multiUser":false}');
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
var mu = getMultiUserFromReq(req);
|
|
468
|
+
if (!mu) {
|
|
469
|
+
res.writeHead(401, { "Content-Type": "application/json" });
|
|
470
|
+
res.end('{"error":"unauthorized"}');
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
var meResp = { multiUser: true, smtpEnabled: smtp.isSmtpConfigured(), emailLoginEnabled: smtp.isEmailLoginEnabled(), user: { id: mu.id, username: mu.username, email: mu.email || null, displayName: mu.displayName, role: mu.role } };
|
|
474
|
+
meResp.permissions = users.getEffectivePermissions(mu, osUsers);
|
|
475
|
+
if (mu.mustChangePin) meResp.mustChangePin = true;
|
|
476
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
477
|
+
res.end(JSON.stringify(meResp));
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// --- Skills routes (delegated to server-skills) ---
|
|
482
|
+
if (skills.handleRequest(req, res, fullUrl)) return;
|
|
483
|
+
|
|
484
|
+
// Root path — redirect to first accessible project
|
|
485
|
+
if (fullUrl === "/" && req.method === "GET") {
|
|
486
|
+
if (!isRequestAuthed(req)) {
|
|
487
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
488
|
+
res.end(auth.getAuthPage());
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (projects.size > 0) {
|
|
492
|
+
var targetSlug = null;
|
|
493
|
+
var reqUser = users.isMultiUser() ? getMultiUserFromReq(req) : null;
|
|
494
|
+
// Check for last-visited project cookie
|
|
495
|
+
var lastProject = parseCookies(req)["clay_last_project"];
|
|
496
|
+
if (lastProject && projects.has(lastProject)) {
|
|
497
|
+
if (reqUser && onGetProjectAccess) {
|
|
498
|
+
var lpAccess = onGetProjectAccess(lastProject);
|
|
499
|
+
if (lpAccess && !lpAccess.error && users.canAccessProject(reqUser.id, lpAccess)) {
|
|
500
|
+
targetSlug = lastProject;
|
|
501
|
+
}
|
|
502
|
+
} else {
|
|
503
|
+
targetSlug = lastProject;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// Fall back to first accessible project
|
|
507
|
+
if (!targetSlug) {
|
|
508
|
+
projects.forEach(function (ctx, s) {
|
|
509
|
+
if (targetSlug) return;
|
|
510
|
+
if (reqUser && onGetProjectAccess) {
|
|
511
|
+
var access = onGetProjectAccess(s);
|
|
512
|
+
if (access && !access.error && users.canAccessProject(reqUser.id, access)) {
|
|
513
|
+
targetSlug = s;
|
|
514
|
+
}
|
|
515
|
+
} else {
|
|
516
|
+
targetSlug = s;
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
if (targetSlug) {
|
|
521
|
+
res.writeHead(302, { "Location": "/p/" + targetSlug + "/" });
|
|
522
|
+
res.end();
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
// No accessible projects — show info page
|
|
527
|
+
if (users.isMultiUser()) {
|
|
528
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
529
|
+
res.end(pages.noProjectsPageHtml());
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
res.writeHead(200, { "Content-Type": "text/plain" });
|
|
533
|
+
res.end("No projects registered.");
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// Global info endpoint (projects only for authenticated requests)
|
|
538
|
+
if (req.method === "GET" && req.url === "/info") {
|
|
539
|
+
if (!isRequestAuthed(req)) {
|
|
540
|
+
res.writeHead(401, {
|
|
541
|
+
"Content-Type": "application/json",
|
|
542
|
+
"Access-Control-Allow-Origin": "*",
|
|
543
|
+
});
|
|
544
|
+
res.end(JSON.stringify({ version: currentVersion, authenticated: false }));
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
var projectList = [];
|
|
548
|
+
projects.forEach(function (ctx, slug) {
|
|
549
|
+
projectList.push({ slug: slug, project: ctx.project });
|
|
550
|
+
});
|
|
551
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
552
|
+
res.end(JSON.stringify({ projects: projectList, version: currentVersion, authenticated: true }));
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// Static files (favicon, manifest, icons, sw.js, etc.)
|
|
557
|
+
if (!fullUrl.includes("..") && !fullUrl.startsWith("/p/") && !fullUrl.startsWith("/api/")) {
|
|
558
|
+
if (serveStatic(fullUrl, res)) return;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Project-scoped routes: /p/{slug}/...
|
|
562
|
+
var slug = extractSlug(req.url.split("?")[0]);
|
|
563
|
+
if (!slug) {
|
|
564
|
+
// Not a project route and not handled above
|
|
565
|
+
res.writeHead(404);
|
|
566
|
+
res.end("Not found");
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
var ctx = projects.get(slug);
|
|
571
|
+
if (!ctx) {
|
|
572
|
+
res.writeHead(302, { "Location": "/" });
|
|
573
|
+
res.end();
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// Redirect /p/{slug} → /p/{slug}/ (trailing slash required for relative paths)
|
|
578
|
+
if (fullUrl === "/p/" + slug) {
|
|
579
|
+
res.writeHead(301, { "Location": "/p/" + slug + "/" });
|
|
580
|
+
res.end();
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// Auth check for project routes
|
|
585
|
+
// Bypass auth for MCP bridge endpoint (localhost only).
|
|
586
|
+
// The mcp-bridge-server.js runs as a local child process and cannot carry cookies.
|
|
587
|
+
var projectUrlForAuth = stripPrefix(req.url.split("?")[0], slug);
|
|
588
|
+
// req.socket.remoteAddress may differ between HTTP/HTTPS (TLSSocket wraps net.Socket).
|
|
589
|
+
// Also check req.connection.remoteAddress for compatibility.
|
|
590
|
+
var remoteAddr = req.socket.remoteAddress
|
|
591
|
+
|| (req.connection && req.connection.remoteAddress)
|
|
592
|
+
|| "";
|
|
593
|
+
var isLocalhost = remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1";
|
|
594
|
+
var isMcpBridgeLocal = projectUrlForAuth === "/api/mcp-bridge"
|
|
595
|
+
&& req.method === "POST"
|
|
596
|
+
&& isLocalhost;
|
|
597
|
+
if (projectUrlForAuth === "/api/mcp-bridge") {
|
|
598
|
+
console.log("[server] MCP bridge auth: method=" + req.method + " addr=" + remoteAddr + " bypass=" + isMcpBridgeLocal);
|
|
599
|
+
}
|
|
600
|
+
if (!isMcpBridgeLocal && !isRequestAuthed(req)) {
|
|
601
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
602
|
+
res.end(auth.getAuthPage());
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// Set last-visited project cookie for root redirect
|
|
607
|
+
res.setHeader("Set-Cookie", "clay_last_project=" + slug + "; Path=/; SameSite=Strict; Max-Age=31536000" + (tlsOptions ? "; Secure" : ""));
|
|
608
|
+
|
|
609
|
+
// Multi-user: check project access for HTTP requests
|
|
610
|
+
if (users.isMultiUser() && onGetProjectAccess) {
|
|
611
|
+
var httpUser = getMultiUserFromReq(req);
|
|
612
|
+
if (httpUser) {
|
|
613
|
+
var httpAccess = onGetProjectAccess(slug);
|
|
614
|
+
if (httpAccess && !httpAccess.error && !users.canAccessProject(httpUser.id, httpAccess)) {
|
|
615
|
+
res.writeHead(302, { "Location": "/" });
|
|
616
|
+
res.end();
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// Strip prefix for project-scoped handling
|
|
623
|
+
var projectUrl = stripPrefix(req.url.split("?")[0], slug);
|
|
624
|
+
// Re-attach query string for API routes
|
|
625
|
+
var qsIdx = req.url.indexOf("?");
|
|
626
|
+
var projectUrlWithQS = qsIdx >= 0 ? projectUrl + req.url.substring(qsIdx) : projectUrl;
|
|
627
|
+
|
|
628
|
+
// Attach user info for project HTTP handler (OS-level isolation)
|
|
629
|
+
if (users.isMultiUser()) {
|
|
630
|
+
req._clayUser = getMultiUserFromReq(req);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Try project HTTP handler first (APIs)
|
|
634
|
+
var origUrl = req.url;
|
|
635
|
+
req.url = projectUrlWithQS;
|
|
636
|
+
var handled = ctx.handleHTTP(req, res, projectUrlWithQS);
|
|
637
|
+
req.url = origUrl;
|
|
638
|
+
if (handled) return;
|
|
639
|
+
|
|
640
|
+
// Static files (same assets for all projects)
|
|
641
|
+
if (req.method === "GET") {
|
|
642
|
+
if (serveStatic(projectUrl, res)) return;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
res.writeHead(404);
|
|
646
|
+
res.end("Not found");
|
|
647
|
+
};
|
|
648
|
+
|
|
649
|
+
// --- Server setup ---
|
|
650
|
+
var server;
|
|
651
|
+
if (tlsOptions) {
|
|
652
|
+
server = require("https").createServer(tlsOptions, appHandler);
|
|
653
|
+
} else {
|
|
654
|
+
server = http.createServer(appHandler);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// --- HTTP onboarding server (only when TLS is active) ---
|
|
658
|
+
var onboardingServer = null;
|
|
659
|
+
if (tlsOptions) {
|
|
660
|
+
onboardingServer = http.createServer(function (req, res) {
|
|
661
|
+
var url = req.url.split("?")[0];
|
|
662
|
+
|
|
663
|
+
// CA certificate download
|
|
664
|
+
if (url === "/ca/download" && req.method === "GET" && caContent) {
|
|
665
|
+
res.writeHead(200, {
|
|
666
|
+
"Content-Type": "application/x-pem-file",
|
|
667
|
+
"Content-Disposition": 'attachment; filename="clagentic-ca.pem"',
|
|
668
|
+
});
|
|
669
|
+
res.end(caContent);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Setup page
|
|
674
|
+
if (url === "/setup" && req.method === "GET") {
|
|
675
|
+
var host = req.headers.host || "localhost";
|
|
676
|
+
var hostname = host.split(":")[0];
|
|
677
|
+
var httpsSetupUrl = "https://" + hostname + ":" + portNum;
|
|
678
|
+
var httpSetupUrl = "http://" + hostname + ":" + (portNum + 1);
|
|
679
|
+
var lanMode = /[?&]mode=lan/.test(req.url);
|
|
680
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
681
|
+
res.end(pages.setupPageHtml(httpsSetupUrl, httpSetupUrl, !!caContent, lanMode));
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// /info — CORS-enabled, used by setup page to verify HTTPS
|
|
686
|
+
if (url === "/info" && req.method === "GET") {
|
|
687
|
+
res.writeHead(200, {
|
|
688
|
+
"Content-Type": "application/json",
|
|
689
|
+
"Access-Control-Allow-Origin": "*",
|
|
690
|
+
});
|
|
691
|
+
res.end(JSON.stringify({ version: currentVersion }));
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// Static files at root (favicon, manifest, icons, etc.)
|
|
696
|
+
if (url.lastIndexOf("/") === 0 && !url.includes("..")) {
|
|
697
|
+
if (serveStatic(url, res)) return;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// Everything else → redirect to HTTPS setup
|
|
701
|
+
var hostname = (req.headers.host || "localhost").split(":")[0];
|
|
702
|
+
res.writeHead(302, { "Location": "https://" + hostname + ":" + portNum + "/setup" });
|
|
703
|
+
res.end();
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// --- WebSocket ---
|
|
708
|
+
var wss = new WebSocketServer({ noServer: true });
|
|
709
|
+
|
|
710
|
+
server.on("upgrade", function (req, socket, head) {
|
|
711
|
+
// Origin validation (CSRF prevention)
|
|
712
|
+
var origin = req.headers.origin;
|
|
713
|
+
if (origin) {
|
|
714
|
+
try {
|
|
715
|
+
var originUrl = new URL(origin);
|
|
716
|
+
var originPort = String(originUrl.port || (originUrl.protocol === "https:" ? "443" : "80"));
|
|
717
|
+
// Extract port from Host header for reverse proxy support.
|
|
718
|
+
// Use URL parser to correctly handle IPv6 addresses (e.g. [::1])
|
|
719
|
+
// and infer default port from origin protocol (not backend tlsOptions)
|
|
720
|
+
// so TLS-terminating proxies on :443 with HTTP backends work.
|
|
721
|
+
var hostPort;
|
|
722
|
+
try {
|
|
723
|
+
var hostUrl = new URL(originUrl.protocol + "//" + (req.headers.host || ""));
|
|
724
|
+
hostPort = String(hostUrl.port || (originUrl.protocol === "https:" ? "443" : "80"));
|
|
725
|
+
} catch (e2) {
|
|
726
|
+
hostPort = String(portNum);
|
|
727
|
+
}
|
|
728
|
+
if (originPort !== String(portNum) && originPort !== hostPort) {
|
|
729
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
730
|
+
socket.destroy();
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
} catch (e) {
|
|
734
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
735
|
+
socket.destroy();
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
if (!isRequestAuthed(req)) {
|
|
741
|
+
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
742
|
+
socket.destroy();
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// Extract slug from WS URL: /p/{slug}/ws
|
|
747
|
+
var wsSlug = extractSlug(req.url);
|
|
748
|
+
if (!wsSlug) {
|
|
749
|
+
socket.destroy();
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
var ctx = projects.get(wsSlug);
|
|
754
|
+
if (!ctx) {
|
|
755
|
+
if (debug) console.log("[server] WS rejected: project not found for slug", wsSlug);
|
|
756
|
+
socket.destroy();
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// Attach user info to the WS connection for multi-user filtering
|
|
761
|
+
var wsUser = null;
|
|
762
|
+
if (users.isMultiUser()) {
|
|
763
|
+
wsUser = getMultiUserFromReq(req);
|
|
764
|
+
// Check project access for multi-user mode
|
|
765
|
+
if (wsUser && onGetProjectAccess) {
|
|
766
|
+
// For worktree projects, inherit access from parent
|
|
767
|
+
var accessSlug = (wsSlug.indexOf("--") !== -1) ? wsSlug.split("--")[0] : wsSlug;
|
|
768
|
+
var projectAccess = onGetProjectAccess(accessSlug);
|
|
769
|
+
if (debug) console.log("[server] WS access check:", wsSlug, "user:", wsUser.id, "role:", wsUser.role, "visibility:", projectAccess && projectAccess.visibility, "ownerId:", projectAccess && projectAccess.ownerId, "allowed:", projectAccess && projectAccess.allowedUsers);
|
|
770
|
+
if (projectAccess && !projectAccess.error) {
|
|
771
|
+
if (!users.canAccessProject(wsUser.id, projectAccess)) {
|
|
772
|
+
if (debug) console.log("[server] WS rejected: access denied for", wsUser.id, "on", wsSlug);
|
|
773
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
774
|
+
socket.destroy();
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
wss.handleUpgrade(req, socket, head, function (ws) {
|
|
782
|
+
// Apply rate limiting to WS messages
|
|
783
|
+
var msgCount = 0;
|
|
784
|
+
var msgWindowStart = Date.now();
|
|
785
|
+
var WS_RATE_LIMIT = 60; // messages per second
|
|
786
|
+
var origEmit = ws.emit;
|
|
787
|
+
ws.emit = function (event) {
|
|
788
|
+
if (event === "message") {
|
|
789
|
+
var now = Date.now();
|
|
790
|
+
if (now - msgWindowStart >= 1000) {
|
|
791
|
+
msgCount = 0;
|
|
792
|
+
msgWindowStart = now;
|
|
793
|
+
}
|
|
794
|
+
msgCount++;
|
|
795
|
+
if (msgCount > WS_RATE_LIMIT) {
|
|
796
|
+
try {
|
|
797
|
+
ws.send(JSON.stringify({ type: "error", message: "Rate limit exceeded. Connection will be closed." }));
|
|
798
|
+
ws.close(1008, "Rate limit exceeded");
|
|
799
|
+
} catch (e) {}
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return origEmit.apply(ws, arguments);
|
|
804
|
+
};
|
|
805
|
+
ws._clayUser = wsUser; // attach user context
|
|
806
|
+
var remoteAddr = req.socket.remoteAddress || "";
|
|
807
|
+
ws._clayLocal = (remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1");
|
|
808
|
+
// Clear cross-project unread for this project when client connects
|
|
809
|
+
var unreadMap = getCrossProjectUnread(ws);
|
|
810
|
+
if (unreadMap[wsSlug]) {
|
|
811
|
+
unreadMap[wsSlug] = 0;
|
|
812
|
+
}
|
|
813
|
+
ctx.handleConnection(ws, wsUser);
|
|
814
|
+
});
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
// --- Cross-project unread tracking ---
|
|
818
|
+
// WeakMap<ws, { slug: count }> tracks how many done events happened in other projects
|
|
819
|
+
var crossProjectUnread = new WeakMap();
|
|
820
|
+
|
|
821
|
+
function getCrossProjectUnread(ws) {
|
|
822
|
+
var map = crossProjectUnread.get(ws);
|
|
823
|
+
if (!map) { map = {}; crossProjectUnread.set(ws, map); }
|
|
824
|
+
return map;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function onSessionDone(sourceSlug) {
|
|
828
|
+
// Increment unread for all clients NOT connected to sourceSlug
|
|
829
|
+
projects.forEach(function (ctx, projSlug) {
|
|
830
|
+
if (projSlug === sourceSlug) return;
|
|
831
|
+
ctx.forEachClient(function (ws) {
|
|
832
|
+
var map = getCrossProjectUnread(ws);
|
|
833
|
+
map[sourceSlug] = (map[sourceSlug] || 0) + 1;
|
|
834
|
+
});
|
|
835
|
+
});
|
|
836
|
+
// Trigger a projects_updated broadcast so clients get updated unread counts
|
|
837
|
+
broadcastProcessingChange();
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// --- Debounced broadcast for processing status changes ---
|
|
841
|
+
var processingUpdateTimer = null;
|
|
842
|
+
function broadcastProcessingChange() {
|
|
843
|
+
if (processingUpdateTimer) clearTimeout(processingUpdateTimer);
|
|
844
|
+
processingUpdateTimer = setTimeout(function () {
|
|
845
|
+
processingUpdateTimer = null;
|
|
846
|
+
var allProjectsList = getProjects();
|
|
847
|
+
// Always send per-client to include cross-project unread counts
|
|
848
|
+
projects.forEach(function (ctx, projSlug) {
|
|
849
|
+
ctx.forEachClient(function (ws) {
|
|
850
|
+
var filtered = allProjectsList;
|
|
851
|
+
if (users.isMultiUser() && onGetProjectAccess) {
|
|
852
|
+
var wsUser = ws._clayUser;
|
|
853
|
+
if (wsUser) {
|
|
854
|
+
filtered = allProjectsList.filter(function (p) {
|
|
855
|
+
var access = onGetProjectAccess(p.slug);
|
|
856
|
+
if (!access || access.error) return true;
|
|
857
|
+
return users.canAccessProject(wsUser.id, access);
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// Attach per-project unread counts for this client
|
|
862
|
+
var unreadMap = getCrossProjectUnread(ws);
|
|
863
|
+
var projectsWithUnread = filtered.map(function (p) {
|
|
864
|
+
var copy = {};
|
|
865
|
+
var keys = Object.keys(p);
|
|
866
|
+
for (var i = 0; i < keys.length; i++) copy[keys[i]] = p[keys[i]];
|
|
867
|
+
// For the current project, use session-level unread total
|
|
868
|
+
if (p.slug === projSlug) {
|
|
869
|
+
copy.unread = ctx.sm.getTotalUnread(ws);
|
|
870
|
+
} else {
|
|
871
|
+
copy.unread = unreadMap[p.slug] || 0;
|
|
872
|
+
}
|
|
873
|
+
return copy;
|
|
874
|
+
});
|
|
875
|
+
if (ws.readyState === 1) {
|
|
876
|
+
ws.send(JSON.stringify({
|
|
877
|
+
type: "projects_updated",
|
|
878
|
+
projects: projectsWithUnread,
|
|
879
|
+
projectCount: projectsWithUnread.length,
|
|
880
|
+
removedProjects: getRemovedProjects(ws._clayUser ? ws._clayUser.id : null),
|
|
881
|
+
folderMeta: getFolderMeta(),
|
|
882
|
+
}));
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
});
|
|
886
|
+
}, 200);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// --- Project management ---
|
|
890
|
+
function addProject(cwd, slug, title, icon, projectOwnerId, worktreeMeta, extraOpts) {
|
|
891
|
+
if (projects.has(slug)) return false;
|
|
892
|
+
var extra = extraOpts || {};
|
|
893
|
+
var ctx = createProjectContext({
|
|
894
|
+
cwd: cwd,
|
|
895
|
+
slug: slug,
|
|
896
|
+
title: title || null,
|
|
897
|
+
icon: icon || null,
|
|
898
|
+
folderName: extra.folderName || null,
|
|
899
|
+
preferredAgent: extra.preferredAgent || null,
|
|
900
|
+
projectOwnerId: projectOwnerId || null,
|
|
901
|
+
worktreeMeta: worktreeMeta || null,
|
|
902
|
+
pushModule: pushModule,
|
|
903
|
+
debug: debug,
|
|
904
|
+
dangerouslySkipPermissions: dangerouslySkipPermissions,
|
|
905
|
+
osUsers: osUsers,
|
|
906
|
+
currentVersion: currentVersion,
|
|
907
|
+
lanHost: lanHost,
|
|
908
|
+
port: portNum,
|
|
909
|
+
tls: !!tlsOptions,
|
|
910
|
+
authToken: pinHash || null,
|
|
911
|
+
getProjectCount: function () { return projects.size; },
|
|
912
|
+
getProjectList: function (userId) {
|
|
913
|
+
var list = [];
|
|
914
|
+
projects.forEach(function (ctx, s) {
|
|
915
|
+
var status = ctx.getStatus();
|
|
916
|
+
if (userId && users.isMultiUser() && onGetProjectAccess) {
|
|
917
|
+
var access = onGetProjectAccess(s);
|
|
918
|
+
if (access && !access.error && !users.canAccessProject(userId, access)) return;
|
|
919
|
+
}
|
|
920
|
+
list.push(status);
|
|
921
|
+
});
|
|
922
|
+
return list;
|
|
923
|
+
},
|
|
924
|
+
getAllProjectSessions: function () {
|
|
925
|
+
var allSessions = [];
|
|
926
|
+
projects.forEach(function (pCtx, pSlug) {
|
|
927
|
+
if (pSlug === slug) return; // skip self
|
|
928
|
+
var status = pCtx.getStatus();
|
|
929
|
+
if (status.isWorktree) return;
|
|
930
|
+
var pSm = pCtx.getSessionManager();
|
|
931
|
+
if (!pSm) return;
|
|
932
|
+
var projectTitle = status.title || status.project || pSlug;
|
|
933
|
+
pSm.sessions.forEach(function (s) {
|
|
934
|
+
if (!s.hidden && s.history && s.history.length > 0) {
|
|
935
|
+
s._projectTitle = projectTitle;
|
|
936
|
+
allSessions.push(s);
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
});
|
|
940
|
+
return allSessions;
|
|
941
|
+
},
|
|
942
|
+
getHubSchedules: function () {
|
|
943
|
+
var allSchedules = [];
|
|
944
|
+
projects.forEach(function (ctx, s) {
|
|
945
|
+
var status = ctx.getStatus();
|
|
946
|
+
var recs = ctx.getSchedules();
|
|
947
|
+
for (var i = 0; i < recs.length; i++) {
|
|
948
|
+
// Shallow-copy full record and augment with project metadata
|
|
949
|
+
var copy = {};
|
|
950
|
+
var keys = Object.keys(recs[i]);
|
|
951
|
+
for (var k = 0; k < keys.length; k++) copy[keys[k]] = recs[i][keys[k]];
|
|
952
|
+
copy.projectSlug = s;
|
|
953
|
+
copy.projectTitle = status.title || status.project;
|
|
954
|
+
allSchedules.push(copy);
|
|
955
|
+
}
|
|
956
|
+
});
|
|
957
|
+
return allSchedules;
|
|
958
|
+
},
|
|
959
|
+
// Move a schedule record from one project to another
|
|
960
|
+
moveScheduleToProject: function (recordId, fromSlug, toSlug) {
|
|
961
|
+
var fromCtx = projects.get(fromSlug);
|
|
962
|
+
var toCtx = projects.get(toSlug);
|
|
963
|
+
if (!fromCtx || !toCtx) return { ok: false, error: "Project not found" };
|
|
964
|
+
var recs = fromCtx.getSchedules();
|
|
965
|
+
var rec = null;
|
|
966
|
+
for (var i = 0; i < recs.length; i++) {
|
|
967
|
+
if (recs[i].id === recordId) { rec = recs[i]; break; }
|
|
968
|
+
}
|
|
969
|
+
if (!rec) return { ok: false, error: "Record not found" };
|
|
970
|
+
// Copy full record data
|
|
971
|
+
var data = {};
|
|
972
|
+
var keys = Object.keys(rec);
|
|
973
|
+
for (var k = 0; k < keys.length; k++) data[keys[k]] = rec[keys[k]];
|
|
974
|
+
// Import into target, remove from source
|
|
975
|
+
toCtx.importSchedule(data);
|
|
976
|
+
fromCtx.removeSchedule(recordId);
|
|
977
|
+
return { ok: true };
|
|
978
|
+
},
|
|
979
|
+
// Bulk move all schedules from one project to another
|
|
980
|
+
moveAllSchedulesToProject: function (fromSlug, toSlug) {
|
|
981
|
+
var fromCtx = projects.get(fromSlug);
|
|
982
|
+
var toCtx = projects.get(toSlug);
|
|
983
|
+
if (!fromCtx || !toCtx) return { ok: false, error: "Project not found" };
|
|
984
|
+
var recs = fromCtx.getSchedules();
|
|
985
|
+
for (var i = 0; i < recs.length; i++) {
|
|
986
|
+
var data = {};
|
|
987
|
+
var keys = Object.keys(recs[i]);
|
|
988
|
+
for (var k = 0; k < keys.length; k++) data[keys[k]] = recs[i][keys[k]];
|
|
989
|
+
toCtx.importSchedule(data);
|
|
990
|
+
}
|
|
991
|
+
// Remove all from source
|
|
992
|
+
var ids = recs.map(function (r) { return r.id; });
|
|
993
|
+
for (var j = 0; j < ids.length; j++) {
|
|
994
|
+
fromCtx.removeSchedule(ids[j]);
|
|
995
|
+
}
|
|
996
|
+
return { ok: true };
|
|
997
|
+
},
|
|
998
|
+
// Get schedule count for a project slug
|
|
999
|
+
getScheduleCount: function (slug) {
|
|
1000
|
+
var ctx = projects.get(slug);
|
|
1001
|
+
if (!ctx) return 0;
|
|
1002
|
+
return ctx.getSchedules().length;
|
|
1003
|
+
},
|
|
1004
|
+
onPresenceChange: broadcastPresenceChange,
|
|
1005
|
+
onProcessingChanged: broadcastProcessingChange,
|
|
1006
|
+
onSessionDone: function () { onSessionDone(slug); },
|
|
1007
|
+
onAddProject: onAddProject,
|
|
1008
|
+
onCreateProject: onCreateProject,
|
|
1009
|
+
onCloneProject: onCloneProject,
|
|
1010
|
+
onRemoveProject: onRemoveProject,
|
|
1011
|
+
onCreateWorktree: onCreateWorktree,
|
|
1012
|
+
onReorderProjects: onReorderProjects,
|
|
1013
|
+
onSetProjectTitle: onSetProjectTitle,
|
|
1014
|
+
onSetProjectIcon: onSetProjectIcon,
|
|
1015
|
+
onSetProjectPreferredAgent: onSetProjectPreferredAgent,
|
|
1016
|
+
onSetProjectFolder: onSetProjectFolder,
|
|
1017
|
+
onRenameProjectFolder: onRenameProjectFolder,
|
|
1018
|
+
onSetFolderIcon: onSetFolderIcon,
|
|
1019
|
+
onProjectOwnerChanged: onProjectOwnerChanged,
|
|
1020
|
+
onGetServerDefaultEffort: onGetServerDefaultEffort,
|
|
1021
|
+
onSetServerDefaultEffort: onSetServerDefaultEffort,
|
|
1022
|
+
onGetProjectDefaultEffort: onGetProjectDefaultEffort,
|
|
1023
|
+
onSetProjectDefaultEffort: onSetProjectDefaultEffort,
|
|
1024
|
+
onGetServerDefaultModel: onGetServerDefaultModel,
|
|
1025
|
+
onSetServerDefaultModel: onSetServerDefaultModel,
|
|
1026
|
+
onGetProjectDefaultModel: onGetProjectDefaultModel,
|
|
1027
|
+
onSetProjectDefaultModel: onSetProjectDefaultModel,
|
|
1028
|
+
onGetServerDefaultMode: onGetServerDefaultMode,
|
|
1029
|
+
onSetServerDefaultMode: onSetServerDefaultMode,
|
|
1030
|
+
onGetProjectDefaultMode: onGetProjectDefaultMode,
|
|
1031
|
+
onSetProjectDefaultMode: onSetProjectDefaultMode,
|
|
1032
|
+
onGetServerDefaultBetas: onGetServerDefaultBetas,
|
|
1033
|
+
onSetServerDefaultBetas: onSetServerDefaultBetas,
|
|
1034
|
+
onGetProjectDefaultBetas: onGetProjectDefaultBetas,
|
|
1035
|
+
onSetProjectDefaultBetas: onSetProjectDefaultBetas,
|
|
1036
|
+
onGetProjectMcpServers: onGetProjectMcpServers,
|
|
1037
|
+
onSetProjectMcpServers: onSetProjectMcpServers,
|
|
1038
|
+
onGetDaemonConfig: onGetDaemonConfig,
|
|
1039
|
+
onSetPin: onSetPin,
|
|
1040
|
+
onSetKeepAwake: onSetKeepAwake,
|
|
1041
|
+
onSetImageRetention: onSetImageRetention,
|
|
1042
|
+
onSetUpdateChannel: onSetUpdateChannel,
|
|
1043
|
+
updateChannel: onGetDaemonConfig ? (onGetDaemonConfig().updateChannel || "stable") : "stable",
|
|
1044
|
+
onShutdown: onShutdown,
|
|
1045
|
+
onRestart: onRestart,
|
|
1046
|
+
onDmMessage: handleDmMessage,
|
|
1047
|
+
broadcastAll: broadcastAll,
|
|
1048
|
+
notificationsModule: _globalNotifications,
|
|
1049
|
+
getProject: function (s) { return projects.get(s) || null; },
|
|
1050
|
+
isUserOnline: isUserOnline,
|
|
1051
|
+
});
|
|
1052
|
+
projects.set(slug, ctx);
|
|
1053
|
+
// ctx.warmup() is now deferred to the first websocket connection into
|
|
1054
|
+
// this project (see project-connection.js handleConnection). Warming
|
|
1055
|
+
// every project at startup spawned a CodexAppServer and an mcp-bridge
|
|
1056
|
+
// child for each one, which cost 30+ processes on daemons with many
|
|
1057
|
+
// projects even though the user typically only opens one.
|
|
1058
|
+
scheduleRegistryRefresh();
|
|
1059
|
+
return true;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// --- DM message handler (delegated to server-dm) ---
|
|
1063
|
+
var dmHandler = serverDm.attachDm({
|
|
1064
|
+
users: users,
|
|
1065
|
+
dm: dm,
|
|
1066
|
+
projects: projects,
|
|
1067
|
+
pushModule: pushModule,
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
function scheduleRegistryRefresh() {
|
|
1071
|
+
// Refresh the project registry for all projects after a project change
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function handleDmMessage(ws, msg) {
|
|
1075
|
+
if (dmHandler.handleMessage(ws, msg)) return;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function removeProject(slug) {
|
|
1079
|
+
var ctx = projects.get(slug);
|
|
1080
|
+
if (!ctx) return false;
|
|
1081
|
+
var shutdownResult = ctx.destroy();
|
|
1082
|
+
projects.delete(slug);
|
|
1083
|
+
if (shutdownResult && typeof shutdownResult.catch === "function") {
|
|
1084
|
+
shutdownResult.catch(function(err) {
|
|
1085
|
+
console.error("[server] Project destroy failed for " + slug + ":", err && err.message ? err.message : err);
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
scheduleRegistryRefresh();
|
|
1089
|
+
return true;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
function getProjects() {
|
|
1093
|
+
var list = [];
|
|
1094
|
+
projects.forEach(function (ctx) {
|
|
1095
|
+
list.push(ctx.getStatus());
|
|
1096
|
+
});
|
|
1097
|
+
return list;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function reorderProjects(slugs) {
|
|
1101
|
+
var ordered = new Map();
|
|
1102
|
+
for (var i = 0; i < slugs.length; i++) {
|
|
1103
|
+
var ctx = projects.get(slugs[i]);
|
|
1104
|
+
if (ctx) ordered.set(slugs[i], ctx);
|
|
1105
|
+
}
|
|
1106
|
+
// Append any remaining (safety)
|
|
1107
|
+
projects.forEach(function (ctx, slug) {
|
|
1108
|
+
if (!ordered.has(slug)) ordered.set(slug, ctx);
|
|
1109
|
+
});
|
|
1110
|
+
projects.clear();
|
|
1111
|
+
ordered.forEach(function (ctx, slug) {
|
|
1112
|
+
projects.set(slug, ctx);
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
function setProjectTitle(slug, title) {
|
|
1117
|
+
var ctx = projects.get(slug);
|
|
1118
|
+
if (!ctx) return false;
|
|
1119
|
+
ctx.setTitle(title);
|
|
1120
|
+
return true;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
function setProjectIcon(slug, icon) {
|
|
1124
|
+
var ctx = projects.get(slug);
|
|
1125
|
+
if (!ctx) return false;
|
|
1126
|
+
ctx.setIcon(icon);
|
|
1127
|
+
return true;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
function setProjectFolder(slug, folderName) {
|
|
1131
|
+
var ctx = projects.get(slug);
|
|
1132
|
+
if (!ctx) return false;
|
|
1133
|
+
ctx.setFolderName(folderName);
|
|
1134
|
+
return true;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function setProjectFolderName(oldName, newName) {
|
|
1138
|
+
projects.forEach(function (ctx) {
|
|
1139
|
+
var status = ctx.getStatus();
|
|
1140
|
+
if (status.folderName === oldName) {
|
|
1141
|
+
ctx.setFolderName(newName);
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
return true;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
function setProjectPreferredAgent(slug, agent) {
|
|
1148
|
+
var ctx = projects.get(slug);
|
|
1149
|
+
if (!ctx) return false;
|
|
1150
|
+
ctx.setPreferredAgent(agent);
|
|
1151
|
+
return true;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// Collect all unique users across all projects (for topbar server-wide presence)
|
|
1155
|
+
function getServerUsers() {
|
|
1156
|
+
var seen = {};
|
|
1157
|
+
var list = [];
|
|
1158
|
+
projects.forEach(function (ctx) {
|
|
1159
|
+
ctx.forEachClient(function (ws) {
|
|
1160
|
+
if (!ws._clayUser) return;
|
|
1161
|
+
var u = ws._clayUser;
|
|
1162
|
+
if (seen[u.id]) return;
|
|
1163
|
+
seen[u.id] = true;
|
|
1164
|
+
var p = u.profile || {};
|
|
1165
|
+
list.push({
|
|
1166
|
+
id: u.id,
|
|
1167
|
+
displayName: p.name || u.displayName || u.username,
|
|
1168
|
+
username: u.username,
|
|
1169
|
+
avatarStyle: p.avatarStyle || "thumbs",
|
|
1170
|
+
avatarSeed: p.avatarSeed || u.username,
|
|
1171
|
+
avatarCustom: p.avatarCustom || "",
|
|
1172
|
+
});
|
|
1173
|
+
});
|
|
1174
|
+
});
|
|
1175
|
+
return list;
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
// Debounced broadcast of projects_updated when presence changes
|
|
1179
|
+
// Sends per-user filtered project lists + server-wide user list
|
|
1180
|
+
var presenceTimer = null;
|
|
1181
|
+
function broadcastPresenceChange() {
|
|
1182
|
+
if (presenceTimer) clearTimeout(presenceTimer);
|
|
1183
|
+
presenceTimer = setTimeout(function () {
|
|
1184
|
+
presenceTimer = null;
|
|
1185
|
+
if (!users.isMultiUser()) {
|
|
1186
|
+
broadcastAll({
|
|
1187
|
+
type: "projects_updated",
|
|
1188
|
+
projects: getProjects(),
|
|
1189
|
+
projectCount: projects.size,
|
|
1190
|
+
removedProjects: getRemovedProjects(),
|
|
1191
|
+
folderMeta: getFolderMeta(),
|
|
1192
|
+
});
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
var serverUsers = getServerUsers();
|
|
1196
|
+
var allUsers = users.getAllUsers().map(function (u) {
|
|
1197
|
+
var p = u.profile || {};
|
|
1198
|
+
return {
|
|
1199
|
+
id: u.id,
|
|
1200
|
+
displayName: p.name || u.displayName || u.username,
|
|
1201
|
+
username: u.username,
|
|
1202
|
+
role: u.role,
|
|
1203
|
+
avatarStyle: p.avatarStyle || "thumbs",
|
|
1204
|
+
avatarSeed: p.avatarSeed || u.username,
|
|
1205
|
+
avatarColor: p.avatarColor || "#7c3aed",
|
|
1206
|
+
avatarCustom: p.avatarCustom || "",
|
|
1207
|
+
};
|
|
1208
|
+
});
|
|
1209
|
+
// Build per-user filtered lists, send individually
|
|
1210
|
+
var sentUsers = {};
|
|
1211
|
+
projects.forEach(function (ctx) {
|
|
1212
|
+
ctx.forEachClient(function (ws) {
|
|
1213
|
+
var userId = ws._clayUser ? ws._clayUser.id : null;
|
|
1214
|
+
var key = userId || "__anon__";
|
|
1215
|
+
if (sentUsers[key]) {
|
|
1216
|
+
// Already computed for this user, just send the cached msg
|
|
1217
|
+
ws.send(sentUsers[key]);
|
|
1218
|
+
return;
|
|
1219
|
+
}
|
|
1220
|
+
var filteredProjects = [];
|
|
1221
|
+
projects.forEach(function (pCtx, s) {
|
|
1222
|
+
var status = pCtx.getStatus();
|
|
1223
|
+
if (userId && onGetProjectAccess) {
|
|
1224
|
+
var access = onGetProjectAccess(s);
|
|
1225
|
+
if (access && !access.error && !users.canAccessProject(userId, access)) return;
|
|
1226
|
+
}
|
|
1227
|
+
filteredProjects.push(status);
|
|
1228
|
+
});
|
|
1229
|
+
// Per-user DM data
|
|
1230
|
+
var userDmFavorites = userId ? users.getDmFavorites(userId) : [];
|
|
1231
|
+
var userDmHidden = userId ? users.getDmHidden(userId) : [];
|
|
1232
|
+
var userDmConversations = [];
|
|
1233
|
+
if (userId) {
|
|
1234
|
+
var dmList = dm.getDmList(userId);
|
|
1235
|
+
for (var di = 0; di < dmList.length; di++) {
|
|
1236
|
+
if (userDmHidden.indexOf(dmList[di].otherUserId) === -1) {
|
|
1237
|
+
userDmConversations.push(dmList[di].otherUserId);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
var msgStr = JSON.stringify({
|
|
1242
|
+
type: "projects_updated",
|
|
1243
|
+
projects: filteredProjects,
|
|
1244
|
+
projectCount: projects.size,
|
|
1245
|
+
serverUsers: serverUsers,
|
|
1246
|
+
allUsers: allUsers,
|
|
1247
|
+
dmFavorites: userDmFavorites,
|
|
1248
|
+
dmConversations: userDmConversations,
|
|
1249
|
+
removedProjects: getRemovedProjects(userId),
|
|
1250
|
+
folderMeta: getFolderMeta(),
|
|
1251
|
+
});
|
|
1252
|
+
sentUsers[key] = msgStr;
|
|
1253
|
+
ws.send(msgStr);
|
|
1254
|
+
});
|
|
1255
|
+
});
|
|
1256
|
+
}, 300);
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
function broadcastAll(msg) {
|
|
1260
|
+
projects.forEach(function (ctx) {
|
|
1261
|
+
ctx.send(msg);
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// Send a message to every live ws belonging to a specific user across all projects.
|
|
1266
|
+
// Used by user-targeted notifications (e.g. user-to-user @mentions).
|
|
1267
|
+
function sendToUser(userId, msg) {
|
|
1268
|
+
if (!userId) return;
|
|
1269
|
+
var data = JSON.stringify(msg);
|
|
1270
|
+
projects.forEach(function (ctx) {
|
|
1271
|
+
if (typeof ctx.forEachClient !== "function") return;
|
|
1272
|
+
ctx.forEachClient(function (ws) {
|
|
1273
|
+
if (ws._clayUser && ws._clayUser.id === userId && ws.readyState === 1) {
|
|
1274
|
+
ws.send(data);
|
|
1275
|
+
}
|
|
1276
|
+
});
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
// True if the user has any live ws across any project.
|
|
1281
|
+
function isUserOnline(userId) {
|
|
1282
|
+
if (!userId) return false;
|
|
1283
|
+
var found = false;
|
|
1284
|
+
projects.forEach(function (ctx) {
|
|
1285
|
+
if (found) return;
|
|
1286
|
+
if (typeof ctx.forEachClient !== "function") return;
|
|
1287
|
+
ctx.forEachClient(function (ws) {
|
|
1288
|
+
if (found) return;
|
|
1289
|
+
if (ws._clayUser && ws._clayUser.id === userId && ws.readyState === 1) {
|
|
1290
|
+
found = true;
|
|
1291
|
+
}
|
|
1292
|
+
});
|
|
1293
|
+
});
|
|
1294
|
+
return found;
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
function forEachProject(fn) {
|
|
1298
|
+
projects.forEach(function (ctx, slug) {
|
|
1299
|
+
fn(ctx, slug);
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
function destroyAll() {
|
|
1304
|
+
_externalTrigger.stopWatcher();
|
|
1305
|
+
var shutdowns = [];
|
|
1306
|
+
projects.forEach(function (ctx, slug) {
|
|
1307
|
+
console.log("[server] Destroying project:", slug);
|
|
1308
|
+
var result = ctx.destroy();
|
|
1309
|
+
if (result && typeof result.then === "function") {
|
|
1310
|
+
shutdowns.push(result.catch(function(err) {
|
|
1311
|
+
console.error("[server] Project destroy failed for " + slug + ":", err && err.message ? err.message : err);
|
|
1312
|
+
return false;
|
|
1313
|
+
}));
|
|
1314
|
+
}
|
|
1315
|
+
});
|
|
1316
|
+
projects.clear();
|
|
1317
|
+
return Promise.all(shutdowns);
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// --- Periodic cleanup of old chat images ---
|
|
1321
|
+
var imagesBaseDir = path.join(CONFIG_DIR, "images");
|
|
1322
|
+
function getImageMaxAgeMs() {
|
|
1323
|
+
var days = onGetDaemonConfig ? onGetDaemonConfig().imageRetentionDays : undefined;
|
|
1324
|
+
if (days === undefined) days = 7;
|
|
1325
|
+
if (days === 0) return 0; // 0 = keep forever
|
|
1326
|
+
return days * 24 * 60 * 60 * 1000;
|
|
1327
|
+
}
|
|
1328
|
+
function cleanupOldImages() {
|
|
1329
|
+
var maxAge = getImageMaxAgeMs();
|
|
1330
|
+
if (maxAge === 0) return; // keep forever
|
|
1331
|
+
try {
|
|
1332
|
+
if (!fs.existsSync(imagesBaseDir)) return;
|
|
1333
|
+
var dirs = fs.readdirSync(imagesBaseDir);
|
|
1334
|
+
var now = Date.now();
|
|
1335
|
+
var removed = 0;
|
|
1336
|
+
for (var d = 0; d < dirs.length; d++) {
|
|
1337
|
+
var dirPath = path.join(imagesBaseDir, dirs[d]);
|
|
1338
|
+
try {
|
|
1339
|
+
var stat = fs.statSync(dirPath);
|
|
1340
|
+
if (!stat.isDirectory()) continue;
|
|
1341
|
+
} catch (e) { continue; }
|
|
1342
|
+
var files = fs.readdirSync(dirPath);
|
|
1343
|
+
for (var f = 0; f < files.length; f++) {
|
|
1344
|
+
var filePath = path.join(dirPath, files[f]);
|
|
1345
|
+
try {
|
|
1346
|
+
var fstat = fs.statSync(filePath);
|
|
1347
|
+
if (now - fstat.mtimeMs > maxAge) {
|
|
1348
|
+
fs.unlinkSync(filePath);
|
|
1349
|
+
removed++;
|
|
1350
|
+
}
|
|
1351
|
+
} catch (e) {}
|
|
1352
|
+
}
|
|
1353
|
+
// Remove empty directory
|
|
1354
|
+
try {
|
|
1355
|
+
var remaining = fs.readdirSync(dirPath);
|
|
1356
|
+
if (remaining.length === 0) fs.rmdirSync(dirPath);
|
|
1357
|
+
} catch (e) {}
|
|
1358
|
+
}
|
|
1359
|
+
if (removed > 0) console.log("[images] Cleaned up " + removed + " expired image(s)");
|
|
1360
|
+
} catch (e) {
|
|
1361
|
+
console.error("[images] Cleanup error:", e.message);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
cleanupOldImages();
|
|
1365
|
+
setInterval(cleanupOldImages, 24 * 60 * 60 * 1000);
|
|
1366
|
+
|
|
1367
|
+
return {
|
|
1368
|
+
server: server,
|
|
1369
|
+
onboardingServer: onboardingServer,
|
|
1370
|
+
isTLS: !!tlsOptions,
|
|
1371
|
+
addProject: addProject,
|
|
1372
|
+
removeProject: removeProject,
|
|
1373
|
+
getProjects: getProjects,
|
|
1374
|
+
reorderProjects: reorderProjects,
|
|
1375
|
+
setProjectTitle: setProjectTitle,
|
|
1376
|
+
setProjectIcon: setProjectIcon,
|
|
1377
|
+
setProjectFolder: setProjectFolder,
|
|
1378
|
+
setProjectFolderName: setProjectFolderName,
|
|
1379
|
+
setProjectPreferredAgent: setProjectPreferredAgent,
|
|
1380
|
+
setAuthToken: auth.setAuthToken,
|
|
1381
|
+
setRecovery: auth.setRecovery,
|
|
1382
|
+
clearRecovery: auth.clearRecovery,
|
|
1383
|
+
broadcastAll: broadcastAll,
|
|
1384
|
+
forEachProject: forEachProject,
|
|
1385
|
+
destroyProject: removeProject,
|
|
1386
|
+
destroyAll: destroyAll,
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
module.exports = { createServer: createServer, generateAuthToken: generateAuthToken, verifyPin: verifyPin };
|