clay-server 4.0.0-beta.23 → 4.0.0-beta.24

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.
@@ -342,6 +342,7 @@ function attachConnection(ctx) {
342
342
  tm.detachAll(ws);
343
343
  clients.delete(ws);
344
344
  stopFileWatch(ws);
345
+ stopAllDirWatches(ws);
345
346
  if (clients.size === 0) {
346
347
  stopFileWatch();
347
348
  stopAllDirWatches();
@@ -0,0 +1,223 @@
1
+ var path = require("path");
2
+ var execFileSync = require("child_process").execFileSync;
3
+ var wrapSpawnAsUser = require("./os-users").wrapSpawnAsUser;
4
+
5
+ function attachFileHistory(ctx, access) {
6
+ var cwd = ctx.cwd;
7
+ var sm = ctx.sm;
8
+ var sendTo = ctx.sendTo;
9
+
10
+ function runGit(ws, args, options) {
11
+ options = Object.assign({}, options, { stdio: ["ignore", "pipe", "pipe"] });
12
+ var identity = access.osIdentity(ws);
13
+ if (identity) options = Object.assign({}, options, { uid: identity.uid, gid: identity.gid });
14
+ var command = wrapSpawnAsUser("git", args, options);
15
+ return execFileSync(command.command, command.args, command.options);
16
+ }
17
+
18
+ function handleFileHistory(ws, msg) {
19
+ if (!/^fs_(file_history|git_diff|file_at)$/.test(msg.type)) return false;
20
+ if (typeof msg.path !== "string" || !msg.path || path.isAbsolute(msg.path) ||
21
+ path.relative(cwd, path.resolve(cwd, msg.path)).split(path.sep).indexOf("..") !== -1 ||
22
+ (msg.hash && !/^[a-fA-F0-9]{4,64}$/.test(msg.hash)) ||
23
+ (msg.hash2 && !/^[a-fA-F0-9]{4,64}$/.test(msg.hash2))) {
24
+ sendTo(ws, { type: msg.type + "_result", path: msg.path, error: "Invalid file history request" });
25
+ return true;
26
+ }
27
+ // --- File edit history ---
28
+ if (msg.type === "fs_file_history") {
29
+ var histPath = msg.path;
30
+ if (!histPath) {
31
+ sendTo(ws, { type: "fs_file_history_result", path: histPath, entries: [] });
32
+ return true;
33
+ }
34
+ var absHistPath = path.resolve(cwd, histPath);
35
+ var entries = [];
36
+
37
+ // Collect session edits
38
+ sm.sessions.forEach(function (session) {
39
+ if (!access.canReadSession(ws, session)) return;
40
+ var sessionLocalId = session.localId;
41
+ var sessionTitle = session.title || "Untitled";
42
+ var histLen = session.history.length || 1;
43
+
44
+ for (var hi = 0; hi < session.history.length; hi++) {
45
+ var entry = session.history[hi];
46
+ if (entry.type !== "tool_executing") continue;
47
+ if (entry.name !== "Edit" && entry.name !== "Write") continue;
48
+ if (!entry.input || !entry.input.file_path) continue;
49
+ if (entry.input.file_path !== absHistPath) continue;
50
+
51
+ // Find parent assistant UUID + message snippet by scanning backwards
52
+ var assistantUuid = null;
53
+ var uuidIndex = -1;
54
+ for (var hj = hi - 1; hj >= 0; hj--) {
55
+ if (session.history[hj].type === "message_uuid" && session.history[hj].messageType === "assistant") {
56
+ assistantUuid = session.history[hj].uuid;
57
+ uuidIndex = hj;
58
+ break;
59
+ }
60
+ }
61
+
62
+ // Find user prompt by scanning backwards from the assistant uuid
63
+ var messageSnippet = "";
64
+ var searchFrom = uuidIndex >= 0 ? uuidIndex : hi;
65
+ for (var hk = searchFrom - 1; hk >= 0; hk--) {
66
+ if (session.history[hk].type === "user_message" && session.history[hk].text) {
67
+ messageSnippet = session.history[hk].text.trim().substring(0, 100);
68
+ break;
69
+ }
70
+ }
71
+
72
+ // Collect Claude's explanation: scan backwards from tool_executing
73
+ // to find the nearest delta text block (skipping tool_start).
74
+ // If no delta found immediately before this tool, scan past
75
+ // intervening tool blocks to find the last delta text within
76
+ // the same assistant turn.
77
+ var assistantSnippet = "";
78
+ var deltaChunks = [];
79
+ for (var hd = hi - 1; hd >= 0; hd--) {
80
+ var hEntry = session.history[hd];
81
+ if (hEntry.type === "tool_start") continue;
82
+ if (hEntry.type === "delta" && hEntry.text) {
83
+ deltaChunks.unshift(hEntry.text);
84
+ } else {
85
+ break;
86
+ }
87
+ }
88
+ if (deltaChunks.length === 0) {
89
+ // No delta immediately before; scan past tool blocks
90
+ // to find the nearest preceding delta in the same turn
91
+ for (var hd2 = hi - 1; hd2 >= 0; hd2--) {
92
+ var hEntry2 = session.history[hd2];
93
+ if (hEntry2.type === "tool_start" || hEntry2.type === "tool_executing" || hEntry2.type === "tool_result") continue;
94
+ if (hEntry2.type === "delta" && hEntry2.text) {
95
+ // Found a delta before an earlier tool in the same turn.
96
+ // Collect this contiguous block of deltas.
97
+ for (var hd3 = hd2; hd3 >= 0; hd3--) {
98
+ var hEntry3 = session.history[hd3];
99
+ if (hEntry3.type === "tool_start") continue;
100
+ if (hEntry3.type === "delta" && hEntry3.text) {
101
+ deltaChunks.unshift(hEntry3.text);
102
+ } else {
103
+ break;
104
+ }
105
+ }
106
+ break;
107
+ } else {
108
+ // Hit message_uuid, user_message, etc. Stop.
109
+ break;
110
+ }
111
+ }
112
+ }
113
+ assistantSnippet = deltaChunks.join("").trim().substring(0, 150);
114
+
115
+ // Approximate timestamp: interpolate between session creation and last activity
116
+ var tStart = session.createdAt || 0;
117
+ var tEnd = session.lastActivity || tStart;
118
+ var ts = tStart + Math.floor((hi / histLen) * (tEnd - tStart));
119
+
120
+ var editRecord = {
121
+ source: "session",
122
+ timestamp: ts,
123
+ sessionLocalId: sessionLocalId,
124
+ sessionTitle: sessionTitle,
125
+ assistantUuid: assistantUuid,
126
+ toolId: entry.id,
127
+ messageSnippet: messageSnippet,
128
+ assistantSnippet: assistantSnippet,
129
+ toolName: entry.name,
130
+ };
131
+
132
+ if (entry.name === "Edit") {
133
+ editRecord.old_string = entry.input.old_string || "";
134
+ editRecord.new_string = entry.input.new_string || "";
135
+ } else {
136
+ editRecord.isFullWrite = true;
137
+ }
138
+
139
+ entries.push(editRecord);
140
+ }
141
+ });
142
+
143
+ // Collect git commits
144
+ try {
145
+ var gitLog = runGit(ws,
146
+ ["log", "--format=%H|%at|%an|%s", "--follow", "--", histPath],
147
+ { cwd: cwd, encoding: "utf8", timeout: 5000 }
148
+ );
149
+ var gitLines = gitLog.trim().split("\n");
150
+ for (var gi = 0; gi < gitLines.length; gi++) {
151
+ if (!gitLines[gi]) continue;
152
+ var parts = gitLines[gi].split("|");
153
+ if (parts.length < 4) continue;
154
+ entries.push({
155
+ source: "git",
156
+ hash: parts[0],
157
+ timestamp: parseInt(parts[1], 10) * 1000,
158
+ author: parts[2],
159
+ message: parts.slice(3).join("|"),
160
+ });
161
+ }
162
+ } catch (e) {
163
+ // Not a git repo or file not tracked, that is fine
164
+ }
165
+
166
+ // Sort by timestamp descending (newest first)
167
+ entries.sort(function (a, b) { return b.timestamp - a.timestamp; });
168
+
169
+ sendTo(ws, { type: "fs_file_history_result", path: histPath, entries: entries });
170
+ return true;
171
+ }
172
+
173
+ // --- Git diff for file history ---
174
+ if (msg.type === "fs_git_diff") {
175
+ var diffPath = msg.path;
176
+ var hash = msg.hash;
177
+ var hash2 = msg.hash2 || null;
178
+ if (!diffPath || !hash) {
179
+ sendTo(ws, { type: "fs_git_diff_result", hash: hash, path: diffPath, diff: "", error: "Missing params" });
180
+ return true;
181
+ }
182
+ try {
183
+ var diff;
184
+ if (hash2) {
185
+ diff = runGit(ws, ["diff", hash, hash2, "--", diffPath],
186
+ { cwd: cwd, encoding: "utf8", timeout: 5000 });
187
+ } else {
188
+ diff = runGit(ws, ["show", hash, "--format=", "--", diffPath],
189
+ { cwd: cwd, encoding: "utf8", timeout: 5000 });
190
+ }
191
+ sendTo(ws, { type: "fs_git_diff_result", hash: hash, hash2: hash2, path: diffPath, diff: diff || "" });
192
+ } catch (e) {
193
+ sendTo(ws, { type: "fs_git_diff_result", hash: hash, hash2: hash2, path: diffPath, diff: "", error: e.message });
194
+ }
195
+ return true;
196
+ }
197
+
198
+ // --- File content at a git commit ---
199
+ if (msg.type === "fs_file_at") {
200
+ var atPath = msg.path;
201
+ var atHash = msg.hash;
202
+ if (!atPath || !atHash) {
203
+ sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: "Missing params" });
204
+ return true;
205
+ }
206
+ try {
207
+ // Convert to repo-relative path (git show requires hash:relative/path)
208
+ var atAbsPath = path.resolve(cwd, atPath);
209
+ var atRelPath = path.relative(cwd, atAbsPath);
210
+ var content = runGit(ws, ["show", atHash + ":" + atRelPath],
211
+ { cwd: cwd, encoding: "utf8", timeout: 5000 });
212
+ sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: content });
213
+ } catch (e) {
214
+ sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: e.message });
215
+ }
216
+ return true;
217
+ }
218
+
219
+ return false;
220
+ }
221
+ return { handleFileHistory: handleFileHistory };
222
+ }
223
+ module.exports = { attachFileHistory: attachFileHistory };
@@ -5,7 +5,7 @@ var path = require("path");
5
5
  * Attach file/directory watcher engine to a project context.
6
6
  *
7
7
  * ctx fields:
8
- * cwd, send, sendTo, safePath, BINARY_EXTS, FS_MAX_SIZE, IGNORED_DIRS
8
+ * cwd, send, sendTo, safePath, BINARY_EXTS, FS_MAX_SIZE, IGNORED_DIRS, requestAccess, fsAsUser
9
9
  */
10
10
  function attachFileWatch(ctx) {
11
11
  var cwd = ctx.cwd;
@@ -15,6 +15,19 @@ function attachFileWatch(ctx) {
15
15
  var BINARY_EXTS = ctx.BINARY_EXTS;
16
16
  var FS_MAX_SIZE = ctx.FS_MAX_SIZE;
17
17
  var IGNORED_DIRS = ctx.IGNORED_DIRS;
18
+ var access = ctx.requestAccess;
19
+
20
+ function identityFor(client) {
21
+ if (!access) return null;
22
+ if (!access.canUseFiles(client)) throw new Error("File browser access is not permitted");
23
+ return access.osIdentity(client);
24
+ }
25
+
26
+ function checkedPath(relPath) {
27
+ var resolved = safePath(cwd, relPath);
28
+ if (!resolved) throw new Error("Access denied");
29
+ return resolved;
30
+ }
18
31
 
19
32
  // --- File watcher ---
20
33
  // One open file per websocket client. A project-wide singleton watcher made
@@ -47,18 +60,21 @@ function attachFileWatch(ctx) {
47
60
  }
48
61
  }
49
62
 
50
- function readFileSnapshot(absPath) {
51
- var stat = fs.statSync(absPath);
63
+ function readFileSnapshot(client, relPath) {
64
+ var identity = identityFor(client);
65
+ var absPath = checkedPath(relPath);
66
+ var stat = identity ? ctx.fsAsUser("stat", { file: absPath }, identity) : fs.statSync(absPath);
52
67
  var ext = path.extname(absPath).toLowerCase();
53
68
  if (stat.size > FS_MAX_SIZE || BINARY_EXTS.has(ext)) return null;
69
+ if (identity) return ctx.fsAsUser("read", { file: absPath, readContent: true }, identity);
54
70
  return { content: fs.readFileSync(absPath, "utf8"), size: stat.size };
55
71
  }
56
72
 
57
- function publishFileChanged(key, client, relPath, absPath) {
73
+ function publishFileChanged(key, client, relPath) {
58
74
  var latest = fileWatchers.get(key);
59
75
  if (!latest || latest.relPath !== relPath) return;
60
76
  try {
61
- var snapshot = readFileSnapshot(absPath);
77
+ var snapshot = readFileSnapshot(client, relPath);
62
78
  if (!snapshot) return;
63
79
  if (latest.hasSnapshot && latest.content === snapshot.content && latest.size === snapshot.size) return;
64
80
  latest.hasSnapshot = true;
@@ -97,7 +113,9 @@ function attachFileWatch(ctx) {
97
113
  var parentPath = path.dirname(absPath);
98
114
  var baseName = path.basename(absPath);
99
115
  var initialSnapshot = null;
100
- try { initialSnapshot = readFileSnapshot(absPath); } catch (e) {}
116
+ try { initialSnapshot = readFileSnapshot(client, relPath); } catch (e) {
117
+ return Promise.resolve(false);
118
+ }
101
119
  try {
102
120
  var watcher = fs.watch(parentPath, function (eventType, filename) {
103
121
  if (filename && String(filename) !== baseName) return;
@@ -105,7 +123,7 @@ function attachFileWatch(ctx) {
105
123
  if (!active || active.relPath !== relPath) return;
106
124
  clearTimeout(active.debounce);
107
125
  active.debounce = setTimeout(function () {
108
- publishFileChanged(key, client, relPath, absPath);
126
+ publishFileChanged(key, client, relPath);
109
127
  }, 200);
110
128
  });
111
129
  var resolveReady = null;
@@ -127,7 +145,7 @@ function attachFileWatch(ctx) {
127
145
  // drop them under load. Periodic content reconciliation is the source of
128
146
  // truth and also survives atomic replacements with identical metadata.
129
147
  entry.pollTimer = setInterval(function () {
130
- publishFileChanged(key, client, relPath, absPath);
148
+ publishFileChanged(key, client, relPath);
131
149
  }, 1000);
132
150
  // fs.watch has no readiness event. Reconcile once on the next event-loop
133
151
  // turn so a change between the initial read and native watcher activation
@@ -135,7 +153,7 @@ function attachFileWatch(ctx) {
135
153
  entry.reconcile = setImmediate(function () {
136
154
  var active = fileWatchers.get(key);
137
155
  if (active) active.reconcile = null;
138
- publishFileChanged(key, client, relPath, absPath);
156
+ publishFileChanged(key, client, relPath);
139
157
  if (fileWatchers.get(key) === entry) settleFileWatchReady(entry, true);
140
158
  });
141
159
  watcher.on("error", function () { closeFileWatch(key); });
@@ -155,55 +173,65 @@ function attachFileWatch(ctx) {
155
173
  for (var i = 0; i < keys.length; i++) closeFileWatch(keys[i]);
156
174
  }
157
175
 
158
- // --- Directory watcher ---
159
- var dirWatchers = {}; // relPath -> { watcher, debounce }
176
+ // Directory subscriptions are private to the requesting socket.
177
+ var dirWatchers = new Map();
160
178
 
161
- function startDirWatch(relPath) {
162
- if (dirWatchers[relPath]) return;
163
- var absPath = safePath(cwd, relPath);
164
- if (!absPath) return;
179
+ function readDirectory(client, relPath) {
180
+ var identity = identityFor(client);
181
+ var absPath = checkedPath(relPath);
182
+ var items = identity ? ctx.fsAsUser("list", { dir: absPath }, identity) :
183
+ fs.readdirSync(absPath, { withFileTypes: true }).map(function (item) {
184
+ return { name: item.name, isDir: item.isDirectory() };
185
+ });
186
+ return items.filter(function (item) {
187
+ return !item.isDir || !IGNORED_DIRS.has(item.name);
188
+ }).map(function (item) {
189
+ return { name: item.name, type: item.isDir ? "dir" : "file",
190
+ path: path.relative(cwd, path.join(absPath, item.name)).split(path.sep).join("/") };
191
+ });
192
+ }
193
+
194
+ function startDirWatch(client, relPath) {
195
+ var subscriptions = dirWatchers.get(client);
196
+ if (!subscriptions) { subscriptions = new Map(); dirWatchers.set(client, subscriptions); }
197
+ if (subscriptions.has(relPath)) return;
165
198
  try {
166
- var debounce = null;
167
- var watcher = fs.watch(absPath, function () {
168
- clearTimeout(debounce);
169
- debounce = setTimeout(function () {
170
- // Re-read directory and broadcast to all clients
199
+ readDirectory(client, relPath);
200
+ var entry = { watcher: null, debounce: null };
201
+ entry.watcher = fs.watch(checkedPath(relPath), function () {
202
+ clearTimeout(entry.debounce);
203
+ entry.debounce = setTimeout(function () {
171
204
  try {
172
- var items = fs.readdirSync(absPath, { withFileTypes: true });
173
- var entries = [];
174
- for (var i = 0; i < items.length; i++) {
175
- if (items[i].isDirectory() && IGNORED_DIRS.has(items[i].name)) continue;
176
- entries.push({
177
- name: items[i].name,
178
- type: items[i].isDirectory() ? "dir" : "file",
179
- path: path.relative(cwd, path.join(absPath, items[i].name)).split(path.sep).join("/"),
180
- });
181
- }
182
- send({ type: "fs_dir_changed", path: relPath, entries: entries });
183
- } catch (e) {
184
- stopDirWatch(relPath);
185
- }
205
+ var entries = readDirectory(client, relPath);
206
+ sendTo(client, { type: "fs_dir_changed", path: relPath, entries: entries });
207
+ } catch (e) { stopDirWatch(client, relPath); }
186
208
  }, 300);
187
209
  });
188
- watcher.on("error", function () { stopDirWatch(relPath); });
189
- dirWatchers[relPath] = { watcher: watcher, debounce: debounce };
190
- } catch (e) {}
210
+ entry.watcher.on("error", function () { stopDirWatch(client, relPath); });
211
+ subscriptions.set(relPath, entry);
212
+ } catch (e) {
213
+ if (!subscriptions.size) dirWatchers.delete(client);
214
+ }
191
215
  }
192
216
 
193
- function stopDirWatch(relPath) {
194
- var entry = dirWatchers[relPath];
195
- if (entry) {
196
- clearTimeout(entry.debounce);
197
- try { entry.watcher.close(); } catch (e) {}
198
- delete dirWatchers[relPath];
199
- }
217
+ function stopDirWatch(client, relPath) {
218
+ var subscriptions = dirWatchers.get(client);
219
+ var entry = subscriptions && subscriptions.get(relPath);
220
+ if (!entry) return;
221
+ clearTimeout(entry.debounce);
222
+ try { entry.watcher.close(); } catch (e) {}
223
+ subscriptions.delete(relPath);
224
+ if (!subscriptions.size) dirWatchers.delete(client);
200
225
  }
201
226
 
202
- function stopAllDirWatches() {
203
- var paths = Object.keys(dirWatchers);
204
- for (var i = 0; i < paths.length; i++) {
205
- stopDirWatch(paths[i]);
206
- }
227
+ function stopAllDirWatches(client) {
228
+ var clients = arguments.length ? [client] : Array.from(dirWatchers.keys());
229
+ clients.forEach(function (key) {
230
+ var subscriptions = dirWatchers.get(key);
231
+ if (subscriptions) Array.from(subscriptions.keys()).forEach(function (relPath) {
232
+ stopDirWatch(key, relPath);
233
+ });
234
+ });
207
235
  }
208
236
 
209
237
  return {
@@ -1,6 +1,7 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
- var execFileSync = require("child_process").execFileSync;
3
+ var attachRequestAccess = require("./project-request-access").attachRequestAccess;
4
+ var attachFileHistory = require("./project-file-history").attachFileHistory;
4
5
 
5
6
  /**
6
7
  * Attach filesystem-related message handlers to a project context.
@@ -20,17 +21,12 @@ var execFileSync = require("child_process").execFileSync;
20
21
  function attachFilesystem(ctx) {
21
22
  var cwd = ctx.cwd;
22
23
  var slug = ctx.slug;
23
- var osUsers = ctx.osUsers;
24
- var sm = ctx.sm;
25
- var send = ctx.send;
26
24
  var sendTo = ctx.sendTo;
27
25
  var safePath = ctx.safePath;
28
26
  var safeAbsPath = ctx.safeAbsPath;
29
- var getOsUserInfoForWs = ctx.getOsUserInfoForWs;
30
27
  var startFileWatch = ctx.startFileWatch;
31
28
  var stopFileWatch = ctx.stopFileWatch;
32
29
  var startDirWatch = ctx.startDirWatch;
33
- var usersModule = ctx.usersModule;
34
30
  var fsAsUser = ctx.fsAsUser;
35
31
  var validateEnvString = ctx.validateEnvString;
36
32
  var onEnvironmentChanged = ctx.onEnvironmentChanged || function () {};
@@ -40,15 +36,19 @@ function attachFilesystem(ctx) {
40
36
  var IMAGE_EXTS = ctx.IMAGE_EXTS;
41
37
  var FS_MAX_SIZE = ctx.FS_MAX_SIZE;
42
38
 
39
+ var access = ctx.requestAccess || attachRequestAccess(ctx);
40
+ var fileHistory = attachFileHistory(ctx, access);
41
+
43
42
  function handleFilesystemMessage(ws, msg) {
44
- // --- File browser permission gate ---
45
- if (msg.type === "fs_list" || msg.type === "fs_read" || msg.type === "fs_write" || msg.type === "fs_delete" || msg.type === "fs_rename" || msg.type === "fs_mkdir" || msg.type === "fs_upload" || msg.type === "fs_search") {
46
- if (ws._clayUser) {
47
- var fbPerms = usersModule.getEffectivePermissions(ws._clayUser, osUsers);
48
- if (!fbPerms.fileBrowser) {
49
- sendTo(ws, { type: msg.type + "_result", error: "File browser access is not permitted" });
50
- return true;
51
- }
43
+ // Unsubscription must remain available after permission revocation.
44
+ if (/^fs_/.test(msg.type) && msg.type !== "fs_unwatch") {
45
+ if (!access.canUseFiles(ws)) {
46
+ sendTo(ws, { type: msg.type + "_result", error: "File browser access is not permitted" });
47
+ return true;
48
+ }
49
+ try { access.osIdentity(ws); } catch (e) {
50
+ sendTo(ws, { type: msg.type + "_result", error: e.message });
51
+ return true;
52
52
  }
53
53
  }
54
54
 
@@ -56,7 +56,7 @@ function attachFilesystem(ctx) {
56
56
  if (msg.type === "fs_list") {
57
57
  var fsDir = safePath(cwd, msg.path || ".");
58
58
  // In OS user mode, fall back to absolute path resolution (ACL enforces access)
59
- if (!fsDir && getOsUserInfoForWs(ws)) {
59
+ if (!fsDir && access.osIdentity(ws)) {
60
60
  fsDir = safeAbsPath(msg.path);
61
61
  }
62
62
  if (!fsDir) {
@@ -64,7 +64,7 @@ function attachFilesystem(ctx) {
64
64
  return true;
65
65
  }
66
66
  try {
67
- var fsListUserInfo = getOsUserInfoForWs(ws);
67
+ var fsListUserInfo = access.osIdentity(ws);
68
68
  var entries = [];
69
69
  if (fsListUserInfo) {
70
70
  // Run as target OS user to respect Linux file permissions
@@ -92,7 +92,7 @@ function attachFilesystem(ctx) {
92
92
  }
93
93
  sendTo(ws, { type: "fs_list_result", path: msg.path || ".", entries: entries });
94
94
  // Auto-watch the directory for changes
95
- startDirWatch(msg.path || ".");
95
+ startDirWatch(ws, msg.path || ".");
96
96
  } catch (e) {
97
97
  sendTo(ws, { type: "fs_list_result", path: msg.path, entries: [], error: e.message });
98
98
  }
@@ -109,7 +109,7 @@ function attachFilesystem(ctx) {
109
109
  try {
110
110
  var searchResults = [];
111
111
  var MAX_RESULTS = 50;
112
- var searchUserInfo = getOsUserInfoForWs(ws);
112
+ var searchUserInfo = access.osIdentity(ws);
113
113
 
114
114
  function walkDir(dir, relPrefix) {
115
115
  if (searchResults.length >= MAX_RESULTS) return;
@@ -148,7 +148,7 @@ function attachFilesystem(ctx) {
148
148
  // --- fs_read ---
149
149
  if (msg.type === "fs_read") {
150
150
  var fsFile = safePath(cwd, msg.path);
151
- if (!fsFile && getOsUserInfoForWs(ws)) {
151
+ if (!fsFile && access.osIdentity(ws)) {
152
152
  fsFile = safeAbsPath(msg.path);
153
153
  }
154
154
  if (!fsFile) {
@@ -156,7 +156,7 @@ function attachFilesystem(ctx) {
156
156
  return true;
157
157
  }
158
158
  try {
159
- var fsReadUserInfo = getOsUserInfoForWs(ws);
159
+ var fsReadUserInfo = access.osIdentity(ws);
160
160
  var ext = path.extname(fsFile).toLowerCase();
161
161
  if (fsReadUserInfo) {
162
162
  // Run stat and read as target OS user
@@ -197,7 +197,7 @@ function attachFilesystem(ctx) {
197
197
  // --- fs_write ---
198
198
  if (msg.type === "fs_write") {
199
199
  var fsWriteFile = safePath(cwd, msg.path);
200
- if (!fsWriteFile && getOsUserInfoForWs(ws)) {
200
+ if (!fsWriteFile && access.osIdentity(ws)) {
201
201
  fsWriteFile = safeAbsPath(msg.path);
202
202
  }
203
203
  if (!fsWriteFile) {
@@ -205,7 +205,7 @@ function attachFilesystem(ctx) {
205
205
  return true;
206
206
  }
207
207
  try {
208
- var fsWriteUserInfo = getOsUserInfoForWs(ws);
208
+ var fsWriteUserInfo = access.osIdentity(ws);
209
209
  if (fsWriteUserInfo) {
210
210
  fsAsUser("write", { file: fsWriteFile, content: msg.content || "" }, fsWriteUserInfo);
211
211
  } else {
@@ -223,12 +223,12 @@ function attachFilesystem(ctx) {
223
223
  msg.type === "read_global_claude_md" || msg.type === "write_global_claude_md" ||
224
224
  msg.type === "get_shared_env" || msg.type === "set_shared_env" ||
225
225
  msg.type === "transfer_project_owner") {
226
- if (ws._clayUser) {
227
- var psPerms = usersModule.getEffectivePermissions(ws._clayUser, osUsers);
228
- if (!psPerms.projectSettings) {
229
- sendTo(ws, { type: "error", text: "Project settings access is not permitted" });
230
- return true;
231
- }
226
+ var globalSetting = /^(read_global_claude_md|write_global_claude_md|get_shared_env|set_shared_env)$/.test(msg.type);
227
+ var targetSlug = msg.slug || slug;
228
+ if (!access.hasPermission(ws, "projectSettings") ||
229
+ (globalSetting ? !access.isAdmin(ws) : !access.canAccessProject(ws, targetSlug))) {
230
+ sendTo(ws, { type: "error", text: "Project settings access is not permitted" });
231
+ return true;
232
232
  }
233
233
  }
234
234
 
@@ -236,7 +236,7 @@ function attachFilesystem(ctx) {
236
236
  if (msg.type === "get_project_env") {
237
237
  var envrc = "";
238
238
  if (typeof opts.onGetProjectEnv === "function") {
239
- var envResult = opts.onGetProjectEnv(msg.slug);
239
+ var envResult = opts.onGetProjectEnv(targetSlug);
240
240
  envrc = envResult.envrc || "";
241
241
  }
242
242
  sendTo(ws, { type: "project_env_result", slug: msg.slug, envrc: envrc });
@@ -250,7 +250,7 @@ function attachFilesystem(ctx) {
250
250
  sendTo(ws, { type: "set_project_env_result", ok: false, slug: msg.slug, error: envError });
251
251
  return true;
252
252
  }
253
- var setResult = opts.onSetProjectEnv(msg.slug, msg.envrc || "");
253
+ var setResult = opts.onSetProjectEnv(targetSlug, msg.envrc || "");
254
254
  if (setResult.ok) onEnvironmentChanged();
255
255
  sendTo(ws, { type: "set_project_env_result", ok: setResult.ok, slug: msg.slug, error: setResult.error, timing: setResult.ok ? "Applies to newly created coding-agent processes. Active processes keep their current environment." : undefined });
256
256
  } else {
@@ -324,196 +324,7 @@ function attachFilesystem(ctx) {
324
324
  return true;
325
325
  }
326
326
 
327
- // --- File edit history ---
328
- if (msg.type === "fs_file_history") {
329
- var histPath = msg.path;
330
- if (!histPath) {
331
- sendTo(ws, { type: "fs_file_history_result", path: histPath, entries: [] });
332
- return true;
333
- }
334
- var absHistPath = path.resolve(cwd, histPath);
335
- var entries = [];
336
-
337
- // Collect session edits
338
- sm.sessions.forEach(function (session) {
339
- var sessionLocalId = session.localId;
340
- var sessionTitle = session.title || "Untitled";
341
- var histLen = session.history.length || 1;
342
-
343
- for (var hi = 0; hi < session.history.length; hi++) {
344
- var entry = session.history[hi];
345
- if (entry.type !== "tool_executing") continue;
346
- if (entry.name !== "Edit" && entry.name !== "Write") continue;
347
- if (!entry.input || !entry.input.file_path) continue;
348
- if (entry.input.file_path !== absHistPath) continue;
349
-
350
- // Find parent assistant UUID + message snippet by scanning backwards
351
- var assistantUuid = null;
352
- var uuidIndex = -1;
353
- for (var hj = hi - 1; hj >= 0; hj--) {
354
- if (session.history[hj].type === "message_uuid" && session.history[hj].messageType === "assistant") {
355
- assistantUuid = session.history[hj].uuid;
356
- uuidIndex = hj;
357
- break;
358
- }
359
- }
360
-
361
- // Find user prompt by scanning backwards from the assistant uuid
362
- var messageSnippet = "";
363
- var searchFrom = uuidIndex >= 0 ? uuidIndex : hi;
364
- for (var hk = searchFrom - 1; hk >= 0; hk--) {
365
- if (session.history[hk].type === "user_message" && session.history[hk].text) {
366
- messageSnippet = session.history[hk].text.trim().substring(0, 100);
367
- break;
368
- }
369
- }
370
-
371
- // Collect Claude's explanation: scan backwards from tool_executing
372
- // to find the nearest delta text block (skipping tool_start).
373
- // If no delta found immediately before this tool, scan past
374
- // intervening tool blocks to find the last delta text within
375
- // the same assistant turn.
376
- var assistantSnippet = "";
377
- var deltaChunks = [];
378
- for (var hd = hi - 1; hd >= 0; hd--) {
379
- var hEntry = session.history[hd];
380
- if (hEntry.type === "tool_start") continue;
381
- if (hEntry.type === "delta" && hEntry.text) {
382
- deltaChunks.unshift(hEntry.text);
383
- } else {
384
- break;
385
- }
386
- }
387
- if (deltaChunks.length === 0) {
388
- // No delta immediately before; scan past tool blocks
389
- // to find the nearest preceding delta in the same turn
390
- for (var hd2 = hi - 1; hd2 >= 0; hd2--) {
391
- var hEntry2 = session.history[hd2];
392
- if (hEntry2.type === "tool_start" || hEntry2.type === "tool_executing" || hEntry2.type === "tool_result") continue;
393
- if (hEntry2.type === "delta" && hEntry2.text) {
394
- // Found a delta before an earlier tool in the same turn.
395
- // Collect this contiguous block of deltas.
396
- for (var hd3 = hd2; hd3 >= 0; hd3--) {
397
- var hEntry3 = session.history[hd3];
398
- if (hEntry3.type === "tool_start") continue;
399
- if (hEntry3.type === "delta" && hEntry3.text) {
400
- deltaChunks.unshift(hEntry3.text);
401
- } else {
402
- break;
403
- }
404
- }
405
- break;
406
- } else {
407
- // Hit message_uuid, user_message, etc. Stop.
408
- break;
409
- }
410
- }
411
- }
412
- assistantSnippet = deltaChunks.join("").trim().substring(0, 150);
413
-
414
- // Approximate timestamp: interpolate between session creation and last activity
415
- var tStart = session.createdAt || 0;
416
- var tEnd = session.lastActivity || tStart;
417
- var ts = tStart + Math.floor((hi / histLen) * (tEnd - tStart));
418
-
419
- var editRecord = {
420
- source: "session",
421
- timestamp: ts,
422
- sessionLocalId: sessionLocalId,
423
- sessionTitle: sessionTitle,
424
- assistantUuid: assistantUuid,
425
- toolId: entry.id,
426
- messageSnippet: messageSnippet,
427
- assistantSnippet: assistantSnippet,
428
- toolName: entry.name,
429
- };
430
-
431
- if (entry.name === "Edit") {
432
- editRecord.old_string = entry.input.old_string || "";
433
- editRecord.new_string = entry.input.new_string || "";
434
- } else {
435
- editRecord.isFullWrite = true;
436
- }
437
-
438
- entries.push(editRecord);
439
- }
440
- });
441
-
442
- // Collect git commits
443
- try {
444
- var gitLog = execFileSync(
445
- "git", ["log", "--format=%H|%at|%an|%s", "--follow", "--", histPath],
446
- { cwd: cwd, encoding: "utf8", timeout: 5000 }
447
- );
448
- var gitLines = gitLog.trim().split("\n");
449
- for (var gi = 0; gi < gitLines.length; gi++) {
450
- if (!gitLines[gi]) continue;
451
- var parts = gitLines[gi].split("|");
452
- if (parts.length < 4) continue;
453
- entries.push({
454
- source: "git",
455
- hash: parts[0],
456
- timestamp: parseInt(parts[1], 10) * 1000,
457
- author: parts[2],
458
- message: parts.slice(3).join("|"),
459
- });
460
- }
461
- } catch (e) {
462
- // Not a git repo or file not tracked, that is fine
463
- }
464
-
465
- // Sort by timestamp descending (newest first)
466
- entries.sort(function (a, b) { return b.timestamp - a.timestamp; });
467
-
468
- sendTo(ws, { type: "fs_file_history_result", path: histPath, entries: entries });
469
- return true;
470
- }
471
-
472
- // --- Git diff for file history ---
473
- if (msg.type === "fs_git_diff") {
474
- var diffPath = msg.path;
475
- var hash = msg.hash;
476
- var hash2 = msg.hash2 || null;
477
- if (!diffPath || !hash) {
478
- sendTo(ws, { type: "fs_git_diff_result", hash: hash, path: diffPath, diff: "", error: "Missing params" });
479
- return true;
480
- }
481
- try {
482
- var diff;
483
- if (hash2) {
484
- diff = execFileSync("git", ["diff", hash, hash2, "--", diffPath],
485
- { cwd: cwd, encoding: "utf8", timeout: 5000 });
486
- } else {
487
- diff = execFileSync("git", ["show", hash, "--format=", "--", diffPath],
488
- { cwd: cwd, encoding: "utf8", timeout: 5000 });
489
- }
490
- sendTo(ws, { type: "fs_git_diff_result", hash: hash, hash2: hash2, path: diffPath, diff: diff || "" });
491
- } catch (e) {
492
- sendTo(ws, { type: "fs_git_diff_result", hash: hash, hash2: hash2, path: diffPath, diff: "", error: e.message });
493
- }
494
- return true;
495
- }
496
-
497
- // --- File content at a git commit ---
498
- if (msg.type === "fs_file_at") {
499
- var atPath = msg.path;
500
- var atHash = msg.hash;
501
- if (!atPath || !atHash) {
502
- sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: "Missing params" });
503
- return true;
504
- }
505
- try {
506
- // Convert to repo-relative path (git show requires hash:relative/path)
507
- var atAbsPath = path.resolve(cwd, atPath);
508
- var atRelPath = path.relative(cwd, atAbsPath);
509
- var content = execFileSync("git", ["show", atHash + ":" + atRelPath],
510
- { cwd: cwd, encoding: "utf8", timeout: 5000 });
511
- sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: content });
512
- } catch (e) {
513
- sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: e.message });
514
- }
515
- return true;
516
- }
327
+ if (fileHistory.handleFileHistory(ws, msg)) return true;
517
328
 
518
329
  return false;
519
330
  }
@@ -0,0 +1,66 @@
1
+ // Shared authorization for project requests and long-lived file subscriptions.
2
+ function attachRequestAccess(ctx) {
3
+ var users = ctx.usersModule;
4
+ var opts = ctx.opts || {};
5
+
6
+ function isMultiUser() {
7
+ return !!(users && users.isMultiUser && users.isMultiUser());
8
+ }
9
+
10
+ function userFor(ws) {
11
+ var user = ws && ws._clayUser;
12
+ if (user && users.findUserById) return users.findUserById(user.id);
13
+ return user || null;
14
+ }
15
+
16
+ function canAccessProject(ws, slug) {
17
+ if (!isMultiUser()) return true;
18
+ var user = userFor(ws);
19
+ if (!user || typeof slug !== "string" || !slug) return false;
20
+ try {
21
+ return typeof opts.canAccessProjectSlug === "function" && opts.canAccessProjectSlug(user.id, slug) === true;
22
+ } catch (e) { return false; }
23
+ }
24
+
25
+ function permitMessage(ws, msg) {
26
+ if (canAccessProject(ws, ctx.slug) && (!msg.targetSlug || canAccessProject(ws, msg.targetSlug))) return true;
27
+ ctx.sendTo(ws, { type: "error", text: "Project access is not permitted" });
28
+ return false;
29
+ }
30
+
31
+ function hasPermission(ws, permission) {
32
+ var user = userFor(ws);
33
+ if (!user) return !isMultiUser();
34
+ return users.getEffectivePermissions(user, ctx.osUsers)[permission] === true;
35
+ }
36
+
37
+ function canUseFiles(ws) {
38
+ return canAccessProject(ws, ctx.slug) && hasPermission(ws, "fileBrowser");
39
+ }
40
+
41
+ function isAdmin(ws) {
42
+ if (!isMultiUser() && !(ws && ws._clayUser)) return true;
43
+ var user = userFor(ws);
44
+ return !!(user && user.role === "admin");
45
+ }
46
+
47
+ function canReadSession(ws, session) {
48
+ if (!isMultiUser()) return true;
49
+ var user = userFor(ws);
50
+ return !!(user && canAccessProject(ws, ctx.slug) && users.canAccessSession(user.id, session, { visibility: "public" }));
51
+ }
52
+
53
+ function osIdentity(ws) {
54
+ if (!ctx.osUsers) return null;
55
+ var user = userFor(ws);
56
+ if (!user || !user.linuxUser) throw new Error("OS user identity is unavailable");
57
+ var info = ctx.getOsUserInfoForWs({ _clayUser: user });
58
+ if (!info) throw new Error("OS user identity is unavailable");
59
+ return info;
60
+ }
61
+
62
+ return { permitMessage: permitMessage, canAccessProject: canAccessProject, hasPermission: hasPermission,
63
+ canUseFiles: canUseFiles, isAdmin: isAdmin, canReadSession: canReadSession, osIdentity: osIdentity };
64
+ }
65
+
66
+ module.exports = { attachRequestAccess: attachRequestAccess };
package/lib/project.js CHANGED
@@ -26,6 +26,7 @@ var { attachMemory } = require("./project-memory");
26
26
  var { attachMateInteraction } = require("./project-mate-interaction");
27
27
  var { attachUserMention } = require("./project-user-mention");
28
28
  var { attachLoop } = require("./project-loop");
29
+ var { attachRequestAccess } = require("./project-request-access");
29
30
  var { attachFileWatch } = require("./project-file-watch");
30
31
  var { attachHTTP } = require("./project-http");
31
32
  var { attachImage } = require("./project-image");
@@ -513,8 +514,14 @@ function createProjectContext(opts) {
513
514
  getProjectOwnerId: function () { return projectOwnerId; },
514
515
  });
515
516
 
517
+ var _requestAccess = attachRequestAccess({
518
+ slug: slug, opts: opts, usersModule: usersModule, osUsers: osUsers,
519
+ sendTo: sendTo, getOsUserInfoForWs: getOsUserInfoForWs,
520
+ });
521
+
516
522
  // --- File/directory watcher engine (delegated to project-file-watch.js) ---
517
523
  var _fileWatch = attachFileWatch({
524
+ requestAccess: _requestAccess, fsAsUser: fsAsUser,
518
525
  cwd: cwd,
519
526
  send: send,
520
527
  sendTo: sendTo,
@@ -1294,6 +1301,7 @@ function createProjectContext(opts) {
1294
1301
  }
1295
1302
 
1296
1303
  function handleMessage(ws, msg) {
1304
+ if (!_requestAccess.permitMessage(ws, msg)) return;
1297
1305
  // --- Keep-alive (delegated to project-connection.js) ---
1298
1306
  // Answered before any routing so a ping can never be forwarded elsewhere.
1299
1307
  // _connection is assigned later in this factory than the other modules, so
@@ -1770,6 +1778,7 @@ function createProjectContext(opts) {
1770
1778
 
1771
1779
  // --- Filesystem handler (delegated to project-filesystem.js) ---
1772
1780
  var _filesystem = attachFilesystem({
1781
+ requestAccess: _requestAccess,
1773
1782
  cwd: cwd,
1774
1783
  slug: slug,
1775
1784
  osUsers: osUsers,
package/lib/server.js CHANGED
@@ -1276,6 +1276,19 @@ function createServer(opts) {
1276
1276
  workspaceQueryService: workspaceQueryService,
1277
1277
  projectLogsService: projectLogsService,
1278
1278
  mateKnowledgeService: mateKnowledgeService,
1279
+ canAccessProjectSlug: function (userId, targetSlug) {
1280
+ var target = projects.get(targetSlug);
1281
+ if (!target) return false;
1282
+ var status = target.getStatus();
1283
+ var access;
1284
+ if (status.isMate) {
1285
+ access = { visibility: "private", ownerId: status.projectOwnerId, allowedUsers: [] };
1286
+ } else {
1287
+ if (!onGetProjectAccess) return false;
1288
+ access = onGetProjectAccess(status.parentSlug || targetSlug);
1289
+ }
1290
+ return !!(access && !access.error && users.canAccessProject(userId, access));
1291
+ },
1279
1292
  getProjectAccess: function () {
1280
1293
  return onGetProjectAccess ? onGetProjectAccess(slug) : { visibility: "public", ownerId: projectOwnerId || null };
1281
1294
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clay-server",
3
- "version": "4.0.0-beta.23",
3
+ "version": "4.0.0-beta.24",
4
4
  "description": "Self-hosted team workspace for Claude Code and Codex. Multi-user, browser-based, with persistent AI mates.",
5
5
  "bin": {
6
6
  "clay-server": "./bin/cli.js",