@clagentic/console 1.9.0-beta.3 → 1.10.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.
Files changed (146) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. package/lib/sdk-permission-ownership.js +0 -136
@@ -1,6 +1,16 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
- var execFileSync = require("child_process").execFileSync;
3
+ var fileScope = require("./project-file-scope");
4
+ var projectGit = require("./project-git");
5
+
6
+ // Settings that act on the whole machine (not on this project), so the
7
+ // per-user projectSettings permission is not enough: administrators only.
8
+ var ADMIN_ONLY_TYPES = {
9
+ read_global_claude_md: true,
10
+ write_global_claude_md: true,
11
+ get_shared_env: true,
12
+ set_shared_env: true,
13
+ };
4
14
 
5
15
  /**
6
16
  * Attach filesystem-related message handlers to a project context.
@@ -9,13 +19,18 @@ var execFileSync = require("child_process").execFileSync;
9
19
  * cwd, slug, osUsers
10
20
  * sm (session manager)
11
21
  * send, sendTo
12
- * safePath, safeAbsPath (functions)
13
22
  * getOsUserInfoForWs (function)
14
- * startFileWatch, stopFileWatch, startDirWatch (from _fileWatch)
15
- * usersModule, fsAsUser
23
+ * startFileWatch, stopFileWatch, startDirWatch (from _fileWatch; take the ws first)
24
+ * usersModule, projectAccess (lib/project-access.js resolver), fsAsUser
16
25
  * validateEnvString (function)
26
+ * envSlug (slug whose environment text is read and written; a worktree's parent), getEnvOwnerId (function)
17
27
  * opts (for onGetProjectEnv, onSetProjectEnv, onGetSharedEnv, onSetSharedEnv callbacks)
18
- * IGNORED_DIRS, BINARY_EXTS, IMAGE_EXTS, FS_MAX_SIZE (constants)
28
+ * fileAccess from project-file-scope.createFileAccess
29
+ * IGNORED_DIRS, IMAGE_EXTS (constants)
30
+ *
31
+ * The slug every handler acts on is ctx.slug: the per-message gate in
32
+ * project.js has already authorized it. A slug carried in a message is never
33
+ * used.
19
34
  */
20
35
  function attachFilesystem(ctx) {
21
36
  var cwd = ctx.cwd;
@@ -24,79 +39,90 @@ function attachFilesystem(ctx) {
24
39
  var sm = ctx.sm;
25
40
  var send = ctx.send;
26
41
  var sendTo = ctx.sendTo;
27
- var safePath = ctx.safePath;
28
- var safeAbsPath = ctx.safeAbsPath;
29
- var safeClaudePath = ctx.safeClaudePath;
30
42
  var getOsUserInfoForWs = ctx.getOsUserInfoForWs;
31
43
  var startFileWatch = ctx.startFileWatch;
32
44
  var stopFileWatch = ctx.stopFileWatch;
33
45
  var startDirWatch = ctx.startDirWatch;
34
46
  var usersModule = ctx.usersModule;
47
+ var projectAccess = ctx.projectAccess;
35
48
  var fsAsUser = ctx.fsAsUser;
36
49
  var validateEnvString = ctx.validateEnvString;
50
+ // The project's environment text lives on the project it is saved for: a
51
+ // worktree reads and writes its parent's.
52
+ var envSlug = ctx.envSlug || slug;
53
+ var getEnvOwnerId = ctx.getEnvOwnerId || function () { return null; };
37
54
  var opts = ctx.opts;
38
55
  var IGNORED_DIRS = ctx.IGNORED_DIRS;
39
- var BINARY_EXTS = ctx.BINARY_EXTS;
40
56
  var IMAGE_EXTS = ctx.IMAGE_EXTS;
41
- var FS_MAX_SIZE = ctx.FS_MAX_SIZE;
57
+ var fileAccess = ctx.fileAccess;
58
+
59
+ // In multi-user mode the project's environment text applies to the project
60
+ // owner's sessions (lib/runtime-env.js projectEnvApplies), so only the owner
61
+ // or an administrator may read or change it: anyone else would be writing
62
+ // variables into the owner's runtime. Single-user mode has one owner.
63
+ function mayManageProjectEnv(ws) {
64
+ var multiUser = typeof projectAccess.isMultiUser === "function" ? projectAccess.isMultiUser() : true;
65
+ if (!multiUser) return true;
66
+ var user = ws._clagenticUser;
67
+ if (!user) return false;
68
+ if (user.role === "admin") return true;
69
+ var ownerId = getEnvOwnerId();
70
+ return !!ownerId && user.id === ownerId;
71
+ }
72
+
73
+ // The file policy applies to every fs_* message except fs_unwatch, which
74
+ // only releases what the connection already holds.
75
+ function isFileMessage(type) {
76
+ return typeof type === "string" && type.indexOf("fs_") === 0 && type !== "fs_unwatch";
77
+ }
78
+
79
+ // Run read-only git inside the project as the repository's owner (see
80
+ // project-git.js); the connection was authorized before this handler ran.
81
+ function gitFor(args) {
82
+ return projectGit.runGit(args, { cwd: cwd, osUsers: osUsers });
83
+ }
42
84
 
43
85
  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._clagenticUser) {
47
- var fbPerms = usersModule.getEffectivePermissions(ws._clagenticUser, osUsers);
48
- if (!fbPerms.fileBrowser) {
49
- sendTo(ws, { type: msg.type + "_result", error: "File browser access is not permitted" });
50
- return true;
51
- }
86
+ // --- Settings that act beyond this project: administrators only ---
87
+ if (typeof msg.type === "string" && ADMIN_ONLY_TYPES[msg.type] === true) {
88
+ if (!projectAccess.isAdmin(ws._clagenticUser, projectAccess.authOf(ws))) {
89
+ sendTo(ws, { type: "error", text: "Admin access required" });
90
+ return true;
91
+ }
92
+ }
93
+
94
+ // --- File policy gate (fileBrowser permission, OS identity) ---
95
+ if (isFileMessage(msg.type)) {
96
+ var fileError = fileAccess.authorize(ws);
97
+ if (fileError) {
98
+ sendTo(ws, { type: msg.type + "_result", path: msg.path, error: fileError });
99
+ return true;
52
100
  }
53
101
  }
54
102
 
55
103
  // --- fs_list ---
56
104
  if (msg.type === "fs_list") {
57
- var fsDir = safePath(cwd, msg.path || ".");
58
- // In OS user mode, fall back to absolute path resolution (ACL enforces access)
59
- if (!fsDir && getOsUserInfoForWs(ws)) {
60
- fsDir = safeAbsPath(msg.path);
61
- }
62
- // Allow read-only access to paths within ~/.claude/ (e.g. plans/)
63
- if (!fsDir && safeClaudePath) {
64
- fsDir = safeClaudePath(msg.path);
65
- }
105
+ var fsListUserInfo = getOsUserInfoForWs(ws);
106
+ var fsDir = fileScope.resolveReadPath(cwd, msg.path || ".", fsListUserInfo);
66
107
  if (!fsDir) {
67
108
  sendTo(ws, { type: "fs_list_result", path: msg.path, entries: [], error: "Access denied" });
68
109
  return true;
69
110
  }
70
111
  try {
71
- var fsListUserInfo = getOsUserInfoForWs(ws);
72
112
  var entries = [];
73
- if (fsListUserInfo) {
74
- // Run as target OS user to respect Linux file permissions
75
- var rawEntries = fsAsUser("list", { dir: fsDir }, fsListUserInfo);
76
- for (var fi = 0; fi < rawEntries.length; fi++) {
77
- var re = rawEntries[fi];
78
- if (re.isDir && IGNORED_DIRS.has(re.name)) continue;
79
- entries.push({
80
- name: re.name,
81
- type: re.isDir ? "dir" : "file",
82
- path: path.relative(cwd, path.join(fsDir, re.name)).split(path.sep).join("/"),
83
- });
84
- }
85
- } else {
86
- var items = fs.readdirSync(fsDir, { withFileTypes: true });
87
- for (var fi = 0; fi < items.length; fi++) {
88
- var item = items[fi];
89
- if (item.isDirectory() && IGNORED_DIRS.has(item.name)) continue;
90
- entries.push({
91
- name: item.name,
92
- type: item.isDirectory() ? "dir" : "file",
93
- path: path.relative(cwd, path.join(fsDir, item.name)).split(path.sep).join("/"),
94
- });
95
- }
113
+ var items = fileAccess.listDir(ws, fsDir);
114
+ for (var fi = 0; fi < items.length; fi++) {
115
+ var item = items[fi];
116
+ if (item.isDir && IGNORED_DIRS.has(item.name)) continue;
117
+ entries.push({
118
+ name: item.name,
119
+ type: item.isDir ? "dir" : "file",
120
+ path: path.relative(cwd, path.join(fsDir, item.name)).split(path.sep).join("/"),
121
+ });
96
122
  }
97
123
  sendTo(ws, { type: "fs_list_result", path: msg.path || ".", entries: entries });
98
124
  // Auto-watch the directory for changes
99
- startDirWatch(msg.path || ".");
125
+ startDirWatch(ws, msg.path || ".");
100
126
  } catch (e) {
101
127
  sendTo(ws, { type: "fs_list_result", path: msg.path, entries: [], error: e.message });
102
128
  }
@@ -105,7 +131,7 @@ function attachFilesystem(ctx) {
105
131
 
106
132
  // --- fs_search ---
107
133
  if (msg.type === "fs_search") {
108
- var query = (msg.query || "").trim().toLowerCase();
134
+ var query = (typeof msg.query === "string" ? msg.query : "").trim().toLowerCase();
109
135
  if (!query) {
110
136
  sendTo(ws, { type: "fs_search_result", query: msg.query, entries: [] });
111
137
  return true;
@@ -113,19 +139,12 @@ function attachFilesystem(ctx) {
113
139
  try {
114
140
  var searchResults = [];
115
141
  var MAX_RESULTS = 50;
116
- var searchUserInfo = getOsUserInfoForWs(ws);
117
142
 
118
143
  function walkDir(dir, relPrefix) {
119
144
  if (searchResults.length >= MAX_RESULTS) return;
120
145
  var items;
121
146
  try {
122
- if (searchUserInfo) {
123
- items = fsAsUser("list", { dir: dir }, searchUserInfo);
124
- } else {
125
- items = fs.readdirSync(dir, { withFileTypes: true }).map(function (d) {
126
- return { name: d.name, isDir: d.isDirectory() };
127
- });
128
- }
147
+ items = fileAccess.listDir(ws, dir);
129
148
  } catch (e) { return; }
130
149
  for (var i = 0; i < items.length; i++) {
131
150
  if (searchResults.length >= MAX_RESULTS) return;
@@ -151,50 +170,22 @@ function attachFilesystem(ctx) {
151
170
 
152
171
  // --- fs_read ---
153
172
  if (msg.type === "fs_read") {
154
- var fsFile = safePath(cwd, msg.path);
155
- if (!fsFile && getOsUserInfoForWs(ws)) {
156
- fsFile = safeAbsPath(msg.path);
157
- }
158
- // Allow read-only access to paths within ~/.claude/ (e.g. plans/)
159
- if (!fsFile && safeClaudePath) {
160
- fsFile = safeClaudePath(msg.path);
161
- }
173
+ var fsReadUserInfo = getOsUserInfoForWs(ws);
174
+ var fsFile = fileScope.resolveReadPath(cwd, msg.path, fsReadUserInfo);
162
175
  if (!fsFile) {
163
176
  sendTo(ws, { type: "fs_read_result", path: msg.path, error: "Access denied" });
164
177
  return true;
165
178
  }
166
179
  try {
167
- var fsReadUserInfo = getOsUserInfoForWs(ws);
168
- var ext = path.extname(fsFile).toLowerCase();
169
- if (fsReadUserInfo) {
170
- // Run stat and read as target OS user
171
- var statResult = fsAsUser("stat", { file: fsFile }, fsReadUserInfo);
172
- if (statResult.size > FS_MAX_SIZE) {
173
- sendTo(ws, { type: "fs_read_result", path: msg.path, binary: true, size: statResult.size, error: "File too large (" + (statResult.size / 1024 / 1024).toFixed(1) + " MB)" });
174
- return true;
175
- }
176
- if (BINARY_EXTS.has(ext)) {
177
- var result = { type: "fs_read_result", path: msg.path, binary: true, size: statResult.size };
178
- if (IMAGE_EXTS.has(ext)) result.imageUrl = "api/file?path=" + encodeURIComponent(msg.path);
179
- sendTo(ws, result);
180
- return true;
181
- }
182
- var readResult = fsAsUser("read", { file: fsFile, readContent: true }, fsReadUserInfo);
183
- sendTo(ws, { type: "fs_read_result", path: msg.path, content: readResult.content, size: statResult.size });
180
+ var readResult = fileAccess.readFile(ws, fsFile);
181
+ if (readResult.kind === "too_large") {
182
+ sendTo(ws, { type: "fs_read_result", path: msg.path, binary: true, size: readResult.size, error: "File too large (" + (readResult.size / 1024 / 1024).toFixed(1) + " MB)" });
183
+ } else if (readResult.kind === "binary") {
184
+ var result = { type: "fs_read_result", path: msg.path, binary: true, size: readResult.size };
185
+ if (IMAGE_EXTS.has(readResult.ext)) result.imageUrl = "api/file?path=" + encodeURIComponent(msg.path);
186
+ sendTo(ws, result);
184
187
  } else {
185
- var stat = fs.statSync(fsFile);
186
- if (stat.size > FS_MAX_SIZE) {
187
- sendTo(ws, { type: "fs_read_result", path: msg.path, binary: true, size: stat.size, error: "File too large (" + (stat.size / 1024 / 1024).toFixed(1) + " MB)" });
188
- return true;
189
- }
190
- if (BINARY_EXTS.has(ext)) {
191
- var result = { type: "fs_read_result", path: msg.path, binary: true, size: stat.size };
192
- if (IMAGE_EXTS.has(ext)) result.imageUrl = "api/file?path=" + encodeURIComponent(msg.path);
193
- sendTo(ws, result);
194
- return true;
195
- }
196
- var content = fs.readFileSync(fsFile, "utf8");
197
- sendTo(ws, { type: "fs_read_result", path: msg.path, content: content, size: stat.size });
188
+ sendTo(ws, { type: "fs_read_result", path: msg.path, content: readResult.content, size: readResult.size });
198
189
  }
199
190
  } catch (e) {
200
191
  sendTo(ws, { type: "fs_read_result", path: msg.path, error: e.message });
@@ -204,10 +195,7 @@ function attachFilesystem(ctx) {
204
195
 
205
196
  // --- fs_write ---
206
197
  if (msg.type === "fs_write") {
207
- var fsWriteFile = safePath(cwd, msg.path);
208
- if (!fsWriteFile && getOsUserInfoForWs(ws)) {
209
- fsWriteFile = safeAbsPath(msg.path);
210
- }
198
+ var fsWriteFile = fileScope.resolveProjectPath(cwd, msg.path, getOsUserInfoForWs(ws));
211
199
  if (!fsWriteFile) {
212
200
  sendTo(ws, { type: "fs_write_result", path: msg.path, ok: false, error: "Access denied" });
213
201
  return true;
@@ -228,8 +216,6 @@ function attachFilesystem(ctx) {
228
216
 
229
217
  // --- Project settings permission gate ---
230
218
  if (msg.type === "get_project_env" || msg.type === "set_project_env" ||
231
- msg.type === "read_global_claude_md" || msg.type === "write_global_claude_md" ||
232
- msg.type === "get_shared_env" || msg.type === "set_shared_env" ||
233
219
  msg.type === "transfer_project_owner") {
234
220
  if (ws._clagenticUser) {
235
221
  var psPerms = usersModule.getEffectivePermissions(ws._clagenticUser, osUsers);
@@ -244,27 +230,43 @@ function attachFilesystem(ctx) {
244
230
  if (msg.type === "get_project_env") {
245
231
  var envrc = "";
246
232
  var hasEnvrc = false;
247
- if (typeof opts.onGetProjectEnv === "function") {
248
- var envResult = opts.onGetProjectEnv(msg.slug);
233
+ var canManageEnv = mayManageProjectEnv(ws);
234
+ var envMultiUser = typeof projectAccess.isMultiUser === "function" ? projectAccess.isMultiUser() : true;
235
+ if (canManageEnv && typeof opts.onGetProjectEnv === "function") {
236
+ var envResult = opts.onGetProjectEnv(envSlug);
249
237
  envrc = envResult.envrc || "";
250
238
  }
251
239
  try {
252
240
  var envrcPath = path.join(cwd, ".envrc");
253
241
  hasEnvrc = fs.existsSync(envrcPath);
254
242
  } catch (e) {}
255
- sendTo(ws, { type: "project_env_result", slug: msg.slug, envrc: envrc, hasEnvrc: hasEnvrc });
243
+ // appliesTo tells the Settings page whom the text reaches; canEdit that
244
+ // this user may see and change it. No value goes to a user who may not.
245
+ sendTo(ws, {
246
+ type: "project_env_result", slug: slug, envrc: envrc, hasEnvrc: hasEnvrc,
247
+ appliesTo: envMultiUser ? "owner" : "everyone", canEdit: canManageEnv,
248
+ });
256
249
  return true;
257
250
  }
258
251
 
259
252
  if (msg.type === "set_project_env") {
260
253
  if (typeof opts.onSetProjectEnv === "function") {
261
- var envError = validateEnvString(msg.envrc || "");
254
+ if (!mayManageProjectEnv(ws)) {
255
+ sendTo(ws, { type: "set_project_env_result", ok: false, slug: slug, error: "Only the project owner or an administrator can change this project's environment variables" });
256
+ return true;
257
+ }
258
+ if (msg.envrc != null && typeof msg.envrc !== "string") {
259
+ sendTo(ws, { type: "set_project_env_result", ok: false, slug: slug, error: "Invalid value" });
260
+ return true;
261
+ }
262
+ var envText = msg.envrc || "";
263
+ var envError = validateEnvString(envText);
262
264
  if (envError) {
263
- sendTo(ws, { type: "set_project_env_result", ok: false, slug: msg.slug, error: envError });
265
+ sendTo(ws, { type: "set_project_env_result", ok: false, slug: slug, error: envError });
264
266
  return true;
265
267
  }
266
- var setResult = opts.onSetProjectEnv(msg.slug, msg.envrc || "");
267
- sendTo(ws, { type: "set_project_env_result", ok: setResult.ok, slug: msg.slug, error: setResult.error });
268
+ var setResult = opts.onSetProjectEnv(envSlug, envText);
269
+ sendTo(ws, { type: "set_project_env_result", ok: setResult.ok, slug: slug, error: setResult.error });
268
270
  } else {
269
271
  sendTo(ws, { type: "set_project_env_result", ok: false, error: "Not supported" });
270
272
  }
@@ -311,6 +313,10 @@ function attachFilesystem(ctx) {
311
313
 
312
314
  if (msg.type === "set_shared_env") {
313
315
  if (typeof opts.onSetSharedEnv === "function") {
316
+ if (msg.envrc != null && typeof msg.envrc !== "string") {
317
+ sendTo(ws, { type: "set_shared_env_result", ok: false, error: "Invalid value" });
318
+ return true;
319
+ }
314
320
  var sharedEnvError = validateEnvString(msg.envrc || "");
315
321
  if (sharedEnvError) {
316
322
  sendTo(ws, { type: "set_shared_env_result", ok: false, error: sharedEnvError });
@@ -326,12 +332,12 @@ function attachFilesystem(ctx) {
326
332
 
327
333
  // --- File watcher ---
328
334
  if (msg.type === "fs_watch") {
329
- if (msg.path) startFileWatch(msg.path);
335
+ if (msg.path) startFileWatch(ws, msg.path);
330
336
  return true;
331
337
  }
332
338
 
333
339
  if (msg.type === "fs_unwatch") {
334
- stopFileWatch();
340
+ stopFileWatch(ws);
335
341
  return true;
336
342
  }
337
343
 
@@ -342,7 +348,12 @@ function attachFilesystem(ctx) {
342
348
  sendTo(ws, { type: "fs_file_history_result", path: histPath, entries: [] });
343
349
  return true;
344
350
  }
345
- var absHistPath = path.resolve(cwd, histPath);
351
+ var histRelPath = fileScope.resolveGitPath(cwd, histPath);
352
+ if (!histRelPath) {
353
+ sendTo(ws, { type: "fs_file_history_result", path: histPath, entries: [], error: "Access denied" });
354
+ return true;
355
+ }
356
+ var absHistPath = path.resolve(cwd, histRelPath);
346
357
  var entries = [];
347
358
 
348
359
  // Collect session edits.
@@ -353,6 +364,8 @@ function attachFilesystem(ctx) {
353
364
  // disk read does not call loadSessionHistory() and does not mutate
354
365
  // session.history/_historyLoaded/LRU state.
355
366
  sm.sessions.forEach(function (session) {
367
+ // Edits made in a session the caller cannot read stay unseen.
368
+ if (!projectAccess.canReadSession(ws._clagenticUser, session, projectAccess.authOf(ws))) return;
356
369
  var sessionLocalId = session.localId;
357
370
  var sessionTitle = session.title || "Untitled";
358
371
  var history = sm.readSessionHistoryFromDisk(session);
@@ -459,10 +472,7 @@ function attachFilesystem(ctx) {
459
472
 
460
473
  // Collect git commits
461
474
  try {
462
- var gitLog = execFileSync(
463
- "git", ["log", "--format=%H|%at|%an|%s", "--follow", "--", histPath],
464
- { cwd: cwd, encoding: "utf8", timeout: 5000 }
465
- );
475
+ var gitLog = gitFor(["log", "--format=%H|%at|%an|%s", "--follow", "--", histRelPath]);
466
476
  var gitLines = gitLog.trim().split("\n");
467
477
  for (var gi = 0; gi < gitLines.length; gi++) {
468
478
  if (!gitLines[gi]) continue;
@@ -496,14 +506,18 @@ function attachFilesystem(ctx) {
496
506
  sendTo(ws, { type: "fs_git_diff_result", hash: hash, path: diffPath, diff: "", error: "Missing params" });
497
507
  return true;
498
508
  }
509
+ // A revision is an object name, never anything git could read as an option.
510
+ var diffRelPath = fileScope.resolveGitPath(cwd, diffPath);
511
+ if (!projectGit.isCommitHash(hash) || (hash2 && !projectGit.isCommitHash(hash2)) || !diffRelPath) {
512
+ sendTo(ws, { type: "fs_git_diff_result", hash: hash, hash2: hash2, path: diffPath, diff: "", error: "Invalid params" });
513
+ return true;
514
+ }
499
515
  try {
500
516
  var diff;
501
517
  if (hash2) {
502
- diff = execFileSync("git", ["diff", hash, hash2, "--", diffPath],
503
- { cwd: cwd, encoding: "utf8", timeout: 5000 });
518
+ diff = gitFor(["diff", hash, hash2, "--", diffRelPath]);
504
519
  } else {
505
- diff = execFileSync("git", ["show", hash, "--format=", "--", diffPath],
506
- { cwd: cwd, encoding: "utf8", timeout: 5000 });
520
+ diff = gitFor(["show", hash, "--format=", "--", diffRelPath]);
507
521
  }
508
522
  sendTo(ws, { type: "fs_git_diff_result", hash: hash, hash2: hash2, path: diffPath, diff: diff || "" });
509
523
  } catch (e) {
@@ -520,12 +534,14 @@ function attachFilesystem(ctx) {
520
534
  sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: "Missing params" });
521
535
  return true;
522
536
  }
537
+ // git show wants hash:repo-relative-path
538
+ var atRelPath = fileScope.resolveGitPath(cwd, atPath);
539
+ if (!projectGit.isCommitHash(atHash) || !atRelPath) {
540
+ sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: "Invalid params" });
541
+ return true;
542
+ }
523
543
  try {
524
- // Convert to repo-relative path (git show requires hash:relative/path)
525
- var atAbsPath = path.resolve(cwd, atPath);
526
- var atRelPath = path.relative(cwd, atAbsPath);
527
- var content = execFileSync("git", ["show", atHash + ":" + atRelPath],
528
- { cwd: cwd, encoding: "utf8", timeout: 5000 });
544
+ var content = gitFor(["show", atHash + ":" + atRelPath]);
529
545
  sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: content });
530
546
  } catch (e) {
531
547
  sendTo(ws, { type: "fs_file_at_result", hash: atHash, path: atPath, content: "", error: e.message });
@@ -0,0 +1,119 @@
1
+ // Running read-only git on behalf of a connected client.
2
+ //
3
+ // Client-supplied values never reach git unchecked: a revision must be a
4
+ // hex object name (so it cannot be read as an option), and a path must be
5
+ // project-relative (see project-file-scope.resolveGitPath).
6
+ //
7
+ // A repository's own config can name programs git will run (textconv,
8
+ // diff.external, core.fsmonitor, hooks). Those must only ever run with the
9
+ // authority of whoever owns the repository, never with a viewer's:
10
+ // - in os-users mode git runs as the uid that owns the repository (the
11
+ // stat of the .git found by walking up from the project directory, which
12
+ // may be a subdirectory of the repository), not as the connection's user. Who may look at the
13
+ // repository is settled by the access gate before a handler runs;
14
+ // - otherwise git runs as the daemon, as every other daemon action does;
15
+ // - on every call the config-driven programs are switched off, and only
16
+ // committed blobs are read, so no clean/smudge or textconv filter runs
17
+ // over working-tree content.
18
+ // No safe.directory override is ever passed: a repository whose owner git
19
+ // does not trust is refused by git itself.
20
+
21
+ var fs = require("fs");
22
+ var path = require("path");
23
+ var childProcess = require("child_process");
24
+
25
+ var COMMIT_HASH_RE = /^[0-9a-fA-F]{4,64}$/;
26
+
27
+ // Config that would otherwise let a repository run a program.
28
+ var HARDENING_CONFIG = [
29
+ "-c", "core.fsmonitor=false",
30
+ "-c", "core.hooksPath=/dev/null",
31
+ "-c", "diff.external=",
32
+ ];
33
+
34
+ // Subcommands that render diffs, and so consult textconv and external drivers.
35
+ var DIFF_RENDERING = { diff: true, show: true, log: true };
36
+
37
+ function isCommitHash(value) {
38
+ return typeof value === "string" && COMMIT_HASH_RE.test(value);
39
+ }
40
+
41
+ // The directory holding the `.git` entry (a directory, or the file a worktree
42
+ // or submodule uses) that git would discover from `cwd`: the nearest ancestor,
43
+ // `cwd` included. Null when there is none. A project can live in a
44
+ // subdirectory of its repository, so `cwd/.git` alone is not the repository.
45
+ function findRepositoryRoot(cwd) {
46
+ var dir = path.resolve(cwd);
47
+ for (;;) {
48
+ try {
49
+ fs.statSync(path.join(dir, ".git"));
50
+ return dir;
51
+ } catch (e) {
52
+ if (e.code !== "ENOENT" && e.code !== "ENOTDIR") return null;
53
+ }
54
+ var parent = path.dirname(dir);
55
+ if (parent === dir) return null;
56
+ dir = parent;
57
+ }
58
+ }
59
+
60
+ // The uid/gid that owns the repository containing `cwd`. Throws when it cannot
61
+ // be established: an unreadable or missing repository is refused, never run as
62
+ // someone else.
63
+ function repositoryOwner(cwd) {
64
+ var root = findRepositoryRoot(cwd);
65
+ if (!root) throw new Error("Cannot determine the repository owner");
66
+ var st;
67
+ try {
68
+ st = fs.statSync(path.join(root, ".git"));
69
+ } catch (e) {
70
+ throw new Error("Cannot determine the repository owner");
71
+ }
72
+ return { uid: st.uid, gid: st.gid };
73
+ }
74
+
75
+ // The full argv for one call: hardening before the subcommand, and diff
76
+ // rendering told not to run any external or textconv program.
77
+ function buildArgs(args) {
78
+ var out = HARDENING_CONFIG.slice();
79
+ if (!args.length) return out;
80
+ out.push(args[0]);
81
+ if (DIFF_RENDERING[args[0]] === true) out.push("--no-ext-diff", "--no-textconv");
82
+ return out.concat(args.slice(1));
83
+ }
84
+
85
+ // args: git argv after the binary name
86
+ // o: { cwd, osUsers, timeoutMs, exec }
87
+ // exec replaces child_process.execFileSync (tests observe the identity used).
88
+ function runGit(args, o) {
89
+ var execOpts = {
90
+ cwd: o.cwd,
91
+ encoding: "utf8",
92
+ timeout: o.timeoutMs || 5000,
93
+ maxBuffer: 16 * 1024 * 1024,
94
+ stdio: ["ignore", "pipe", "pipe"],
95
+ env: {
96
+ PATH: process.env.PATH,
97
+ HOME: process.env.HOME,
98
+ GIT_TERMINAL_PROMPT: "0",
99
+ GIT_OPTIONAL_LOCKS: "0",
100
+ GIT_CONFIG_NOSYSTEM: "1",
101
+ GIT_CONFIG_GLOBAL: "/dev/null",
102
+ },
103
+ };
104
+ if (o.osUsers) {
105
+ var owner = repositoryOwner(o.cwd);
106
+ execOpts.uid = owner.uid;
107
+ execOpts.gid = owner.gid;
108
+ }
109
+ var exec = o.exec || childProcess.execFileSync;
110
+ return exec("git", buildArgs(args), execOpts);
111
+ }
112
+
113
+ module.exports = {
114
+ isCommitHash: isCommitHash,
115
+ findRepositoryRoot: findRepositoryRoot,
116
+ repositoryOwner: repositoryOwner,
117
+ buildArgs: buildArgs,
118
+ runGit: runGit,
119
+ };