agentgui 1.0.1126 → 1.0.1127
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.
Potentially problematic release.
This version of agentgui might be problematic. Click here for more details.
- package/.gm/browser-config.json +1 -0
- package/.gm/disciplines/agentgui/mem-1779277005143-0-1352.json +1 -0
- package/.gm/disciplines/agentgui/memories/.flat-export-done +0 -0
- package/.gm/disciplines/agentgui/memories/mem-c07fa3b0836edbe2-1352.md +8 -0
- package/.gm/gm.db +0 -0
- package/.gm/memories/.flat-export-done +1 -0
- package/.gm/memories/mem-0131ff4869d86085-370.md +10 -0
- package/.gm/memories/mem-04049d11cb8c1661-2135.md +8 -0
- package/.gm/memories/mem-069ff10372ed1770-1375.md +8 -0
- package/.gm/memories/mem-08a4a9e050a4deff-3048.md +8 -0
- package/.gm/memories/mem-09597ee0df9c9224-965.md +8 -0
- package/.gm/memories/mem-0993d156f571b619-1059.md +8 -0
- package/.gm/memories/mem-0b681bf2340c8df1-3170.md +8 -0
- package/.gm/memories/mem-0c444abde86202f6-1681.md +8 -0
- package/.gm/memories/mem-0d1408fa048b9923-1159.md +8 -0
- package/.gm/memories/mem-0dad5d82fec829ba-887.md +8 -0
- package/.gm/memories/mem-10a776effb7ce3a6-935.md +8 -0
- package/.gm/memories/mem-10d264b4f8e66fb4-1492.md +8 -0
- package/.gm/memories/mem-118c35ac67541d98-2909.md +8 -0
- package/.gm/memories/mem-119cf70dd19aa0a5-2225.md +8 -0
- package/.gm/memories/mem-15a07cd761b337c4-4320.md +8 -0
- package/.gm/memories/mem-15c73aca528535cb-2183.md +8 -0
- package/.gm/memories/mem-166f52796185e0e7-1487.md +8 -0
- package/.gm/memories/mem-1a148cf9c3126df5-3963.md +8 -0
- package/.gm/memories/mem-1a459001058f618e-567.md +8 -0
- package/.gm/memories/mem-1af3e13f7618e668-2146.md +8 -0
- package/.gm/memories/mem-1fd31d6873e9c164-794.md +8 -0
- package/.gm/memories/mem-21f551be092fd77d-2340.md +8 -0
- package/.gm/memories/mem-231ff5de003f20f0-586.md +8 -0
- package/.gm/memories/mem-2567393d3adb03ab-347.md +8 -0
- package/.gm/memories/mem-27faf41cdd050c80-1261.md +8 -0
- package/.gm/memories/mem-28889e43e8ce64cc-3663.md +8 -0
- package/.gm/memories/mem-2f4fd06515abf439-2562.md +8 -0
- package/.gm/memories/mem-34a749430303c5f7-544.md +8 -0
- package/.gm/memories/mem-3602d11d7bce9446-1057.md +8 -0
- package/.gm/memories/mem-38b7e24dbcba2f3e-639.md +8 -0
- package/.gm/memories/mem-39a7cc2f887a90b1-1079.md +8 -0
- package/.gm/memories/mem-40d6169c8759061d-806.md +8 -0
- package/.gm/memories/mem-4420e6d00e5c8632-2318.md +8 -0
- package/.gm/memories/mem-447e5a54ddc9357a-654.md +8 -0
- package/.gm/memories/mem-455b3beb4afabe14-591.md +8 -0
- package/.gm/memories/mem-4845ee594759151c-560.md +8 -0
- package/.gm/memories/mem-4a1254c60b868b88-374.md +8 -0
- package/.gm/memories/mem-4bafafa47a0e4b6c-3237.md +8 -0
- package/.gm/memories/mem-4c06c45b4d31bc60-1202.md +8 -0
- package/.gm/memories/mem-4dfac801d0378448-3676.md +8 -0
- package/.gm/memories/mem-4ecd3b713e384170-122.md +10 -0
- package/.gm/memories/mem-51d8992a3c6f6c9c-1073.md +8 -0
- package/.gm/memories/mem-539eee7e8c6c10ee-2557.md +8 -0
- package/.gm/memories/mem-559b8b2abc4b1091-1665.md +8 -0
- package/.gm/memories/mem-59dd73a463e54948-871.md +8 -0
- package/.gm/memories/mem-5b99b882ffe1a3c2-2262.md +8 -0
- package/.gm/memories/mem-5feb252a5244149c-1791.md +8 -0
- package/.gm/memories/mem-6224f8d185797f2b-1047.md +8 -0
- package/.gm/memories/mem-6434ee8261a6a6a2-3126.md +8 -0
- package/.gm/memories/mem-66b0947b946f3437-1155.md +8 -0
- package/.gm/memories/mem-6bdf783a1f6be7c2-1062.md +8 -0
- package/.gm/memories/mem-6d49f08bebac54c9-744.md +8 -0
- package/.gm/memories/mem-70d96acb736af2d7-685.md +8 -0
- package/.gm/memories/mem-70de7d5e71fcd439-2680.md +8 -0
- package/.gm/memories/mem-713614f12d7029da-1577.md +8 -0
- package/.gm/memories/mem-720d76c88e64f6ee-1967.md +8 -0
- package/.gm/memories/mem-7535f34f430fc196-1340.md +8 -0
- package/.gm/memories/mem-861a588d2773681a-1311.md +8 -0
- package/.gm/memories/mem-8af7980a92e09959-891.md +8 -0
- package/.gm/memories/mem-8b438ef4c609b7af-401.md +8 -0
- package/.gm/memories/mem-8f59884039787ef3-743.md +8 -0
- package/.gm/memories/mem-92b199c2024ee1aa-2513.md +8 -0
- package/.gm/memories/mem-9329105b05b9c0f6-324.md +10 -0
- package/.gm/memories/mem-94f30cec3c283f97-782.md +10 -0
- package/.gm/memories/mem-956d4813319f65a3-1710.md +8 -0
- package/.gm/memories/mem-96fffbb6615e031b-1263.md +8 -0
- package/.gm/memories/mem-993ab31f7a10aefa-718.md +8 -0
- package/.gm/memories/mem-a3e440db285f655a-995.md +8 -0
- package/.gm/memories/mem-a52933cd6495e6f5-2624.md +8 -0
- package/.gm/memories/mem-a86426ac44138c96-1606.md +8 -0
- package/.gm/memories/mem-a95b1d49d71133ce-1007.md +8 -0
- package/.gm/memories/mem-a9968a186368b022-1150.md +8 -0
- package/.gm/memories/mem-aaeae38d8eb01809-1076.md +8 -0
- package/.gm/memories/mem-ade01d9c02677c55-1557.md +8 -0
- package/.gm/memories/mem-b06b8c85b81663e6-1250.md +8 -0
- package/.gm/memories/mem-b451e5e17e555202-1490.md +8 -0
- package/.gm/memories/mem-b64ad00dcb6f909e-937.md +8 -0
- package/.gm/memories/mem-b7d6018ceca55b6f-2220.md +8 -0
- package/.gm/memories/mem-bdf466854032cac9-1509.md +8 -0
- package/.gm/memories/mem-c0482039e6ab4c50-2047.md +8 -0
- package/.gm/memories/mem-c4aaec5c4e6f80c2-920.md +8 -0
- package/.gm/memories/mem-c66976ddacb4fbe8-1454.md +8 -0
- package/.gm/memories/mem-c7c5bc263850c332-1844.md +8 -0
- package/.gm/memories/mem-cda639547932c796-713.md +8 -0
- package/.gm/memories/mem-cdf04ff6a6a0aa6f-671.md +8 -0
- package/.gm/memories/mem-cf8472c84d9e04c4-1883.md +8 -0
- package/.gm/memories/mem-cfd4d894370c63c3-1288.md +8 -0
- package/.gm/memories/mem-d060480435f92eec-1146.md +8 -0
- package/.gm/memories/mem-d347c921b79e6d44-1099.md +8 -0
- package/.gm/memories/mem-d3c8ea6c861bfbb8-1457.md +8 -0
- package/.gm/memories/mem-d5e928c552cd87f9-214.md +10 -0
- package/.gm/memories/mem-d63bc3b8a0269844-406.md +10 -0
- package/.gm/memories/mem-d9c19257abc2fa5e-1061.md +8 -0
- package/.gm/memories/mem-d9f26358a7cd3bb8-866.md +8 -0
- package/.gm/memories/mem-da1c91acf63d81d3-863.md +8 -0
- package/.gm/memories/mem-dc1ac3b04d22317e-664.md +8 -0
- package/.gm/memories/mem-dceeae20bc56d407-711.md +8 -0
- package/.gm/memories/mem-dd98b21c0896dc04-1557.md +8 -0
- package/.gm/memories/mem-df74674eec7745ac-178.md +10 -0
- package/.gm/memories/mem-dfe3b466fd5d1199-802.md +8 -0
- package/.gm/memories/mem-e0f9286aed2d5a06-1116.md +8 -0
- package/.gm/memories/mem-e1950b064099b7be-1895.md +8 -0
- package/.gm/memories/mem-e1d5431ae2542872-961.md +8 -0
- package/.gm/memories/mem-e490a181de6469fc-487.md +8 -0
- package/.gm/memories/mem-e72c6efbb27326fb-392.md +8 -0
- package/.gm/memories/mem-e943b58115a02b4c-593.md +8 -0
- package/.gm/memories/mem-e9bc5f9ed6edbcf7-1580.md +8 -0
- package/.gm/memories/mem-eae1e383927854fb-2649.md +8 -0
- package/.gm/memories/mem-ebbe6c0694c526f0-1392.md +8 -0
- package/.gm/memories/mem-ebf85becc23410b0-1633.md +8 -0
- package/.gm/memories/mem-ee0596fa17c7102e-362.md +10 -0
- package/.gm/memories/mem-ee4450fbc311b583-1361.md +8 -0
- package/.gm/memories/mem-ee8858162518f144-1252.md +8 -0
- package/.gm/memories/mem-f3297e82df622649-1166.md +8 -0
- package/.gm/memories/mem-f3f317c083d979ee-1210.md +8 -0
- package/.gm/memories/mem-f714a86465fba158-2041.md +8 -0
- package/.gm/memories/mem-f786bc1626d92845-204.md +10 -0
- package/.gm/memories/mem-f9f0dc8895b21e18-1217.md +8 -0
- package/.gm/memories/mem-fb3b2a7395800041-525.md +8 -0
- package/.gm/memories/mem-fc5753f92ee7d654-966.md +8 -0
- package/.gm/memories/mem-fe3faa1652f07239-480.md +8 -0
- package/.gm/memories/mem-ff8669e527e5c427-2788.md +8 -0
- package/.gm/mutables.yml +53 -0
- package/.gm/prd.yml +3342 -1
- package/AGENTS.md +122 -122
- package/UX_OPTIMIZATION_SUMMARY.md +238 -0
- package/agentgui-after.png +0 -0
- package/agentgui-current.png +0 -0
- package/agentgui-final.png +0 -0
- package/agentgui-nobrand.png +0 -0
- package/agentgui-now.png +0 -0
- package/agentgui-v2.png +0 -0
- package/agentgui-v4.png +0 -0
- package/bash.exe.stackdump +28 -0
- package/database.js +110 -109
- package/design-reference.png +0 -0
- package/lib/acp-sdk-manager.js +9 -42
- package/lib/claude-runner-acp.js +155 -213
- package/lib/claude-runner-agents.js +157 -170
- package/lib/http-handler.js +931 -400
- package/lib/ws-handlers-util.js +466 -11
- package/package.json +1 -1
- package/site/app/js/app.js +4741 -4221
- package/site/app/js/backend.js +602 -621
- package/site/app/vendor/anentrypoint-design/247420.css +13673 -14799
- package/site/app/vendor/anentrypoint-design/247420.js +449 -735
- package/.gm/.embed-generation.code_chunks +0 -1
- package/.gm/.embed-generation.git_commit_vectors +0 -1
- package/.gm/.embed-generation.memories +0 -1
- package/.gm/.embed-generation.rssearch_vectors +0 -1
- package/lib/acp-http-protocol.js +0 -95
- package/lib/http-routes/mutations.js +0 -199
- package/lib/http-routes/reads.js +0 -212
- package/lib/http-routes/shared.js +0 -225
- package/lib/ws-handlers/agents.js +0 -137
- package/lib/ws-handlers/chat.js +0 -157
- package/lib/ws-handlers/git.js +0 -159
- package/lib/ws-handlers/misc.js +0 -36
- package/lib/ws-handlers/shared.js +0 -47
- package/lib/ws-handlers/terminal-state.js +0 -16
- package/site/app/js/chat-persistence.js +0 -123
- package/site/app/js/hash-routing.js +0 -62
- package/site/app/js/history.js +0 -435
- package/site/app/js/shortcuts.js +0 -128
package/lib/http-handler.js
CHANGED
|
@@ -1,400 +1,931 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import os from 'os';
|
|
4
|
-
import crypto from 'crypto';
|
|
5
|
-
import * as term from './terminal.js';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
//
|
|
345
|
-
if (
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
if (
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import crypto from 'crypto';
|
|
5
|
+
import * as term from './terminal.js';
|
|
6
|
+
|
|
7
|
+
// Confine a requested filesystem path to an allowlist of roots. Two layers:
|
|
8
|
+
// 1. normalize + resolved-prefix check on the LEXICAL path (blocks `../`
|
|
9
|
+
// traversal, which path.normalize collapses so a literal `..` test is a
|
|
10
|
+
// no-op);
|
|
11
|
+
// 2. fs.realpathSync + the SAME prefix check on the REAL path, so a symlink
|
|
12
|
+
// that lives inside an allowed root but points outside it cannot escape
|
|
13
|
+
// (the lexical path passes layer 1, the resolved target fails layer 2).
|
|
14
|
+
// Returns { ok, realPath, reason }. realPath is the symlink-resolved absolute
|
|
15
|
+
// path to stat/read; callers use it, never the raw input. A non-existent path
|
|
16
|
+
// has no realpath yet, so it fails closed with reason 'not found'.
|
|
17
|
+
// Mask ?token=VALUE in a URL string before logging so credentials never
|
|
18
|
+
// appear in server logs or error messages.
|
|
19
|
+
export function maskToken(url) {
|
|
20
|
+
if (typeof url !== 'string') return url;
|
|
21
|
+
return url.replace(/([?&]token=)[^&]*/gi, '$1***');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Module-level platform constant — never changes at runtime.
|
|
25
|
+
const IS_WINDOWS = os.platform() === 'win32';
|
|
26
|
+
|
|
27
|
+
export function confineToRoots(inputPath, allowRoots) {
|
|
28
|
+
const norms = allowRoots.map(r => path.normalize(r));
|
|
29
|
+
const expanded = inputPath && inputPath.startsWith('~') ? inputPath.replace('~', os.homedir()) : inputPath;
|
|
30
|
+
const normalizedPath = path.normalize(expanded || '');
|
|
31
|
+
const isAbsolute = IS_WINDOWS ? /^[A-Za-z]:[\\/]/.test(normalizedPath) : normalizedPath.startsWith('/');
|
|
32
|
+
const within = (p) => {
|
|
33
|
+
const np = IS_WINDOWS ? p.toLowerCase() : p;
|
|
34
|
+
return norms.some(root => {
|
|
35
|
+
const r = IS_WINDOWS ? root.toLowerCase() : root;
|
|
36
|
+
return np === r || np.startsWith(r + path.sep);
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
if (!isAbsolute || !within(normalizedPath)) return { ok: false, reason: 'path outside allowed roots' };
|
|
40
|
+
// realpath the target and re-confine, defeating symlink escape (TOCTOU/link
|
|
41
|
+
// traversal). If realpath throws (missing path / broken link) fail closed.
|
|
42
|
+
let realPath;
|
|
43
|
+
try { realPath = fs.realpathSync(normalizedPath); }
|
|
44
|
+
catch (e) { return { ok: false, reason: e && e.code === 'ENOENT' ? 'not found' : 'cannot resolve path', code: e && e.code }; }
|
|
45
|
+
if (!within(realPath)) return { ok: false, reason: 'symlink target outside allowed roots' };
|
|
46
|
+
return { ok: true, realPath };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Secret-bearing basenames that must never be readable through ANY confined
|
|
50
|
+
// raw-bytes route (preview or download), even when they sit inside an allowed
|
|
51
|
+
// root: dotfiles, env/key/cert material, and credential stores. One const so
|
|
52
|
+
// /api/file and /api/download can never drift apart.
|
|
53
|
+
export const SECRET_RE = /(^\.|\.(env|pem|key|crt|p12|pfx)$|secret|credential|\.npmrc$|\.netrc$)/i;
|
|
54
|
+
|
|
55
|
+
// The allowlist the Files surface operates within: server cwd + Claude
|
|
56
|
+
// projects dir, widened via FS_ROOTS (path-separated). One construction so
|
|
57
|
+
// /api/list,file,download and the mutation routes can never drift apart.
|
|
58
|
+
export function fsAllowRoots() {
|
|
59
|
+
const roots = [
|
|
60
|
+
process.env.CLAUDE_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects'),
|
|
61
|
+
];
|
|
62
|
+
// The server cwd is only exposed when PASSWORD is set (the witnessed
|
|
63
|
+
// localhost-PASSWORD deploy lists the repo tree) or FS_ALLOW_CWD=1 is opted
|
|
64
|
+
// in. An open no-PASSWORD deploy must NOT expose the whole server tree.
|
|
65
|
+
if (process.env.PASSWORD || process.env.FS_ALLOW_CWD === '1') {
|
|
66
|
+
roots.push(process.env.STARTUP_CWD || process.cwd());
|
|
67
|
+
}
|
|
68
|
+
if (process.env.FS_ROOTS) roots.push(...process.env.FS_ROOTS.split(path.delimiter));
|
|
69
|
+
return roots.map(r => path.normalize(r));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// A new file/dir name must be a single path component: no separators, no
|
|
73
|
+
// traversal, no NTFS alternate-data-stream colon, no reserved Windows device
|
|
74
|
+
// names, no trailing dot/space (Windows silently strips them, aliasing two
|
|
75
|
+
// names onto one entry). Returns the trimmed name or null when inadmissible.
|
|
76
|
+
function sanitizeEntryName(name) {
|
|
77
|
+
if (typeof name !== 'string') return null;
|
|
78
|
+
const n = name.trim();
|
|
79
|
+
if (!n || n.length > 255) return null;
|
|
80
|
+
if (/[\\/:*?"<>|\x00-\x1f]/.test(n)) return null;
|
|
81
|
+
if (n === '.' || n === '..') return null;
|
|
82
|
+
if (/[. ]$/.test(n)) return null;
|
|
83
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(n)) return null;
|
|
84
|
+
return n;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Every confined filesystem route accepts its target path via a `?path=`/
|
|
88
|
+
// `?dir=` query param, preferred over a path SEGMENT. A reverse proxy's
|
|
89
|
+
// proxy_pass URI normalization can decode-then-reencode the request path,
|
|
90
|
+
// collapsing an encoded %2F segment slash back into a literal '/' before
|
|
91
|
+
// forwarding - the app then sees extra path segments instead of one opaque
|
|
92
|
+
// one, strips what it thinks is a leading '/', and silently turns an absolute
|
|
93
|
+
// path into a relative one that fails confinement even for genuinely
|
|
94
|
+
// accessible directories/files. A query param is untouched by that
|
|
95
|
+
// normalization on any proxy in front of this app. `legacyPrefix` is the old
|
|
96
|
+
// `/api/xxx/<path>` route prefix, still accepted for any caller not yet
|
|
97
|
+
// updated to the query-param form.
|
|
98
|
+
function resolveConfinedPath(req, routePath, queryKey, legacyPrefix) {
|
|
99
|
+
const url = new URL(req.url, 'http://x');
|
|
100
|
+
const qVal = url.searchParams.get(queryKey);
|
|
101
|
+
if (qVal != null) return qVal;
|
|
102
|
+
const raw = routePath.split('?')[0].slice(legacyPrefix.length).replace(/^\//, '');
|
|
103
|
+
return raw ? decodeURIComponent(raw) : '';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Map a Node.js filesystem error code to a safe human-readable string that
|
|
107
|
+
// does not disclose host paths or internal stack context. Used everywhere an
|
|
108
|
+
// err.message would otherwise be returned to the client.
|
|
109
|
+
function safeErrMsg(err) {
|
|
110
|
+
if (!err) return 'unknown error';
|
|
111
|
+
switch (err.code) {
|
|
112
|
+
case 'ENOENT': return 'file not found';
|
|
113
|
+
case 'EACCES': return 'permission denied';
|
|
114
|
+
case 'EPERM': return 'operation not permitted';
|
|
115
|
+
case 'EISDIR': return 'path is a directory';
|
|
116
|
+
case 'ENOTDIR': return 'path is not a directory';
|
|
117
|
+
case 'ENOTEMPTY': return 'directory is not empty';
|
|
118
|
+
case 'EEXIST': return 'file already exists';
|
|
119
|
+
case 'EXDEV': return 'cannot move across drives';
|
|
120
|
+
case 'EMFILE': return 'too many open files';
|
|
121
|
+
case 'ENOSPC': return 'no space left on device';
|
|
122
|
+
default: return 'operation failed';
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Read a request body with a hard size cap; resolves a Buffer or rejects with
|
|
127
|
+
// .code='TOO_LARGE' so the caller can answer 413 without buffering the rest.
|
|
128
|
+
function readBody(req, maxBytes) {
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const chunks = []; let total = 0;
|
|
131
|
+
req.on('data', (c) => {
|
|
132
|
+
total += c.length;
|
|
133
|
+
if (total > maxBytes) { const e = new Error('body too large'); e.code = 'TOO_LARGE'; req.destroy(); reject(e); return; }
|
|
134
|
+
chunks.push(c);
|
|
135
|
+
});
|
|
136
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
137
|
+
req.on('error', reject);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// True when the resolved path IS one of the allowlist roots - the roots
|
|
142
|
+
// themselves are never mutation targets (rename/delete of a root would orphan
|
|
143
|
+
// the whole surface).
|
|
144
|
+
function isAllowRoot(realPath, allowRoots) {
|
|
145
|
+
const p = IS_WINDOWS ? realPath.toLowerCase() : realPath;
|
|
146
|
+
return allowRoots.some(r => (IS_WINDOWS ? r.toLowerCase() : r) === p);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// --- Soft-delete (trash) -----------------------------------------------
|
|
150
|
+
// /api/delete moves entries into <root>/.agentgui-trash/<trashId>__<name>
|
|
151
|
+
// instead of unlinking, giving a short undo window. In-memory index only
|
|
152
|
+
// (server restart forfeits the undo window - acceptable since the retention
|
|
153
|
+
// window itself is short and this is a convenience net on top of, not a
|
|
154
|
+
// replacement for, the pre-delete ConfirmDialog). Purged after
|
|
155
|
+
// TRASH_RETENTION_MS or when trashIndex grows past TRASH_MAX_ENTRIES
|
|
156
|
+
// (oldest-first), so a long-running server's trash dir can't grow unbounded.
|
|
157
|
+
const TRASH_DIR_NAME = '.agentgui-trash';
|
|
158
|
+
const TRASH_RETENTION_MS = parseInt(process.env.AGENTGUI_TRASH_RETENTION_MS || '', 10) || 10 * 60 * 1000;
|
|
159
|
+
const TRASH_MAX_ENTRIES = 200;
|
|
160
|
+
const trashIndex = new Map(); // trashId -> { trashPath, originalPath, root, deletedAt }
|
|
161
|
+
|
|
162
|
+
function purgeExpiredTrash() {
|
|
163
|
+
const now = Date.now();
|
|
164
|
+
for (const [id, info] of trashIndex) {
|
|
165
|
+
if (now - info.deletedAt > TRASH_RETENTION_MS) {
|
|
166
|
+
try { fs.rmSync(info.trashPath, { recursive: true, force: true }); } catch { /* already gone */ }
|
|
167
|
+
trashIndex.delete(id);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (trashIndex.size > TRASH_MAX_ENTRIES) {
|
|
171
|
+
const sorted = [...trashIndex.entries()].sort((a, b) => a[1].deletedAt - b[1].deletedAt);
|
|
172
|
+
for (const [id, info] of sorted.slice(0, trashIndex.size - TRASH_MAX_ENTRIES)) {
|
|
173
|
+
try { fs.rmSync(info.trashPath, { recursive: true, force: true }); } catch {}
|
|
174
|
+
trashIndex.delete(id);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Which allowed root a confined realPath lives under - the trash dir sits
|
|
180
|
+
// alongside it (still inside the SAME root, so confineToRoots covers the
|
|
181
|
+
// trash path too - no new unconfined surface).
|
|
182
|
+
function rootFor(realPath, allowRoots) {
|
|
183
|
+
const p = IS_WINDOWS ? realPath.toLowerCase() : realPath;
|
|
184
|
+
return allowRoots.find(r => { const rr = IS_WINDOWS ? r.toLowerCase() : r; return p === rr || p.startsWith(rr + path.sep); });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function moveToTrash(realPath, allowRoots) {
|
|
188
|
+
purgeExpiredTrash();
|
|
189
|
+
const root = rootFor(realPath, allowRoots);
|
|
190
|
+
if (!root) { const e = new Error('not confined to an allowed root'); e.code = 'EACCES'; throw e; }
|
|
191
|
+
const trashDir = path.join(root, TRASH_DIR_NAME);
|
|
192
|
+
fs.mkdirSync(trashDir, { recursive: true });
|
|
193
|
+
const trashId = crypto.randomBytes(8).toString('hex');
|
|
194
|
+
const base = path.basename(realPath);
|
|
195
|
+
const trashPath = path.join(trashDir, trashId + '__' + base);
|
|
196
|
+
fs.renameSync(realPath, trashPath);
|
|
197
|
+
trashIndex.set(trashId, { trashPath, originalPath: realPath, root, deletedAt: Date.now() });
|
|
198
|
+
return { trashId };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function restoreFromTrash(trashId, allowRoots) {
|
|
202
|
+
const info = trashIndex.get(trashId);
|
|
203
|
+
if (!info) { const e = new Error('nothing to restore - the undo window has expired or this was already restored'); e.code = 'NOT_FOUND'; throw e; }
|
|
204
|
+
// Re-confine the ORIGINAL path at restore time (not trust the cached one
|
|
205
|
+
// blindly) - the allowlist itself doesn't change at runtime, but this keeps
|
|
206
|
+
// restore honoring the exact same confinement contract every other route does.
|
|
207
|
+
const conf = confineToRoots(info.originalPath, allowRoots);
|
|
208
|
+
if (!conf.ok && conf.reason !== 'not found') { const e = new Error('restore target is no longer inside an accessible folder'); e.code = 'CONFLICT'; throw e; }
|
|
209
|
+
if (fs.existsSync(info.originalPath)) { const e = new Error('a file already exists at the original location'); e.code = 'CONFLICT'; throw e; }
|
|
210
|
+
fs.mkdirSync(path.dirname(info.originalPath), { recursive: true });
|
|
211
|
+
fs.renameSync(info.trashPath, info.originalPath);
|
|
212
|
+
trashIndex.delete(trashId);
|
|
213
|
+
return { path: info.originalPath };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function createHttpHandler({ BASE_URL, expressApp, queries, sendJSON, serveFile, staticDir, messageQueues, getWss, activeExecutions, getACPStatus, discoveredAgents, PKG_VERSION, RATE_LIMIT_MAX, rateLimitMap, routes, PORT }) {
|
|
217
|
+
// Warn operators when CORS_ORIGIN=* is combined with no PASSWORD: any
|
|
218
|
+
// cross-origin page can make credentialless fetch() calls to all /api/*
|
|
219
|
+
// endpoints (list, file, download, rename, delete, mkdir) and read or
|
|
220
|
+
// modify the filesystem. The existing code is structurally correct (no
|
|
221
|
+
// Access-Control-Allow-Credentials with wildcard), but the exposure is
|
|
222
|
+
// easy to miss.
|
|
223
|
+
if (process.env.CORS_ORIGIN === '*' && !process.env.PASSWORD) {
|
|
224
|
+
console.warn('[agentgui] WARNING: CORS_ORIGIN=* is set without PASSWORD. Any cross-origin page can make credentialless requests to all /api/* endpoints and read/modify the filesystem. Set PASSWORD or restrict CORS_ORIGIN to a specific origin.');
|
|
225
|
+
}
|
|
226
|
+
return async function httpHandler(req, res) {
|
|
227
|
+
// CORS: emit ACAO only when CORS_ORIGIN is explicitly set. A wildcard would
|
|
228
|
+
// let any webpage the user visits make credentialless fetches to /api/list,
|
|
229
|
+
// /api/file/*, etc. and read ~/.claude/projects content — even on a no-
|
|
230
|
+
// PASSWORD localhost deploy. Set CORS_ORIGIN=<origin> for cross-origin tools.
|
|
231
|
+
const _corsOrigin = process.env.CORS_ORIGIN;
|
|
232
|
+
if (_corsOrigin) {
|
|
233
|
+
// Never set a wildcard when credentials (cookies) may be in play — a
|
|
234
|
+
// wildcard + credentials is rejected by browsers and leaks session tokens.
|
|
235
|
+
// A specific origin allows credentialed cross-origin requests safely.
|
|
236
|
+
res.setHeader('Access-Control-Allow-Origin', _corsOrigin);
|
|
237
|
+
if (_corsOrigin !== '*') res.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
238
|
+
res.setHeader('Vary', 'Origin');
|
|
239
|
+
// Allow-Methods and Allow-Headers are only meaningful on CORS preflights
|
|
240
|
+
// or CORS requests; emitting them unconditionally leaks the method surface
|
|
241
|
+
// to same-origin (and non-CORS) responses unnecessarily.
|
|
242
|
+
if (req.method === 'OPTIONS' || req.headers['origin']) {
|
|
243
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
|
244
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
245
|
+
}
|
|
246
|
+
} // no ACAO header -> browsers enforce same-origin by default
|
|
247
|
+
// The password can ride in a ?token= query param (EventSource/deep-links
|
|
248
|
+
// can't set headers), so a navigation away from the app would leak it in
|
|
249
|
+
// the Referer header to the destination. Strip the referrer on every
|
|
250
|
+
// response so the credential never crosses an origin boundary that way.
|
|
251
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
252
|
+
// Prevent MIME-sniffing attacks on all responses including file downloads.
|
|
253
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
254
|
+
// Emit HSTS when the connection is known-TLS so clients pin HTTPS and
|
|
255
|
+
// refuse future downgrade attempts (protects cookie + ?token= in transit).
|
|
256
|
+
if (req.socket.encrypted || req.headers['x-forwarded-proto'] === 'https') {
|
|
257
|
+
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
|
|
258
|
+
}
|
|
259
|
+
// CSP: the markdown stack (marked/dompurify/prismjs) and the DS kit load
|
|
260
|
+
// from unpkg/jsdelivr; everything else is self. connect-src also allows
|
|
261
|
+
// self for the same-origin WS/SSE. script-src drops 'unsafe-inline' in
|
|
262
|
+
// favour of a per-request nonce threaded onto every server-injected and
|
|
263
|
+
// static inline <script> (bootstrap, hot-reload, importmap) by the asset
|
|
264
|
+
// server. style-src keeps 'unsafe-inline' because the DS injects a runtime
|
|
265
|
+
// <style> with no hook to nonce.
|
|
266
|
+
const cspNonce = crypto.randomBytes(16).toString('base64');
|
|
267
|
+
res.setHeader('Content-Security-Policy', [
|
|
268
|
+
"default-src 'self'",
|
|
269
|
+
`script-src 'self' 'nonce-${cspNonce}' https://unpkg.com https://cdn.jsdelivr.net`,
|
|
270
|
+
"style-src 'self' 'unsafe-inline' https://unpkg.com https://cdn.jsdelivr.net https://fonts.googleapis.com",
|
|
271
|
+
"img-src 'self' data: blob:",
|
|
272
|
+
"font-src 'self' data: https://unpkg.com https://cdn.jsdelivr.net https://fonts.gstatic.com",
|
|
273
|
+
"connect-src 'self' https://unpkg.com https://cdn.jsdelivr.net ws: wss:",
|
|
274
|
+
"object-src 'none'",
|
|
275
|
+
"base-uri 'self'",
|
|
276
|
+
"frame-ancestors 'self'",
|
|
277
|
+
].join('; '));
|
|
278
|
+
if (req.method === 'OPTIONS') { res.writeHead(200); res.end(); return; }
|
|
279
|
+
if (req.headers.upgrade && req.headers.upgrade.toLowerCase() === 'websocket') return;
|
|
280
|
+
|
|
281
|
+
// Only honour X-Forwarded-For behind a trusted proxy (TRUST_PROXY=1), and
|
|
282
|
+
// then take the RIGHT-MOST hop (the one the trusted proxy itself observed,
|
|
283
|
+
// not a client-spoofed left-most value). Otherwise the socket peer is the
|
|
284
|
+
// only trustworthy source - a client can forge the header freely.
|
|
285
|
+
let clientIp;
|
|
286
|
+
if (process.env.TRUST_PROXY === '1' && req.headers['x-forwarded-for']) {
|
|
287
|
+
const hops = req.headers['x-forwarded-for'].split(',').map(s => s.trim()).filter(Boolean);
|
|
288
|
+
clientIp = hops[hops.length - 1] || req.socket.remoteAddress;
|
|
289
|
+
} else {
|
|
290
|
+
clientIp = req.socket.remoteAddress;
|
|
291
|
+
}
|
|
292
|
+
// Normalize IPv4-mapped IPv6 addresses (::ffff:1.2.3.4 -> 1.2.3.4) so the
|
|
293
|
+
// rate-limit bucket is the same regardless of how the OS presents the peer.
|
|
294
|
+
if (clientIp && clientIp.startsWith('::ffff:')) clientIp = clientIp.slice(7);
|
|
295
|
+
const hits = (rateLimitMap.get(clientIp) || 0) + 1;
|
|
296
|
+
rateLimitMap.set(clientIp, hits);
|
|
297
|
+
res.setHeader('X-RateLimit-Limit', RATE_LIMIT_MAX);
|
|
298
|
+
res.setHeader('X-RateLimit-Remaining', Math.max(0, RATE_LIMIT_MAX - hits));
|
|
299
|
+
if (hits > RATE_LIMIT_MAX) { res.writeHead(429, { 'Retry-After': '60' }); res.end('Too Many Requests'); return; }
|
|
300
|
+
|
|
301
|
+
const _pwd = process.env.PASSWORD;
|
|
302
|
+
// Optional: exempt /health from auth so container/k8s probes work
|
|
303
|
+
// without distributing the password to monitoring infra.
|
|
304
|
+
const _bareEarly = req.url.split('?')[0];
|
|
305
|
+
const _healthExempt = process.env.HEALTH_NO_AUTH === '1' && (_bareEarly === '/health' || _bareEarly === '/api/health' || _bareEarly === (BASE_URL + '/health') || _bareEarly === (BASE_URL + '/api/health'));
|
|
306
|
+
if (_pwd && !_healthExempt) {
|
|
307
|
+
const _auth = req.headers['authorization'] || '';
|
|
308
|
+
let _ok = false;
|
|
309
|
+
// Constant-time compare over fixed-width SHA-256 digests so neither the
|
|
310
|
+
// password length nor a byte-position mismatch leaks via timing.
|
|
311
|
+
const _checkToken = (tok) => {
|
|
312
|
+
try {
|
|
313
|
+
const a = crypto.createHash('sha256').update(String(tok)).digest();
|
|
314
|
+
const b = crypto.createHash('sha256').update(String(_pwd)).digest();
|
|
315
|
+
return crypto.timingSafeEqual(a, b);
|
|
316
|
+
} catch { return false; }
|
|
317
|
+
};
|
|
318
|
+
if (_auth.startsWith('Basic ')) {
|
|
319
|
+
try {
|
|
320
|
+
const _decoded = Buffer.from(_auth.slice(6), 'base64').toString('utf8');
|
|
321
|
+
const _ci = _decoded.indexOf(':');
|
|
322
|
+
if (_ci !== -1) _ok = _checkToken(_decoded.slice(_ci + 1));
|
|
323
|
+
} catch (_) {}
|
|
324
|
+
} else if (_auth.startsWith('Bearer ')) {
|
|
325
|
+
const bearerToken = _auth.slice(7);
|
|
326
|
+
// Validate Bearer token format: non-empty, no whitespace. Prevents
|
|
327
|
+
// timing-attack length inference if PASSWORD contains spaces.
|
|
328
|
+
if (/^[\S]+$/.test(bearerToken)) _ok = _checkToken(bearerToken);
|
|
329
|
+
}
|
|
330
|
+
// EventSource and same-origin links can't set headers - accept ?token= as fallback.
|
|
331
|
+
let _viaQuery = false;
|
|
332
|
+
if (!_ok) {
|
|
333
|
+
try {
|
|
334
|
+
const _qsTok = new URL(req.url, 'http://localhost').searchParams.get('token');
|
|
335
|
+
if (_qsTok) { _ok = _checkToken(_qsTok); _viaQuery = _ok; }
|
|
336
|
+
} catch (_) {}
|
|
337
|
+
}
|
|
338
|
+
// Static subresources (js/css/vendor) are requested by the BROWSER, which
|
|
339
|
+
// can attach neither a header nor a ?token= - without a cookie the SPA
|
|
340
|
+
// can never boot behind PASSWORD (index.html 200s, app.js 401s, blank
|
|
341
|
+
// page). On any successful auth, set an HttpOnly SameSite=Lax cookie the
|
|
342
|
+
// gate accepts for subsequent requests. Lax + the CSRF guard below keep
|
|
343
|
+
// cross-site mutations rejected; the value is URL-encoded (a password
|
|
344
|
+
// may carry cookie-hostile characters like commas).
|
|
345
|
+
if (!_ok) {
|
|
346
|
+
try {
|
|
347
|
+
const _ck = req.headers['cookie'] || '';
|
|
348
|
+
const _m = /(?:^|;\s*)agentgui_token=([^;]+)/.exec(_ck);
|
|
349
|
+
if (_m) _ok = _checkToken(decodeURIComponent(_m[1]));
|
|
350
|
+
} catch (_) {}
|
|
351
|
+
} else if (_viaQuery || _auth) {
|
|
352
|
+
try {
|
|
353
|
+
// Secure only over a real TLS connection (or behind an https proxy /
|
|
354
|
+
// explicit opt-in) so the localhost-http witness still gets a usable
|
|
355
|
+
// cookie. Max-Age bounds the credential's lifetime to a day.
|
|
356
|
+
const _https = req.socket.encrypted || req.headers['x-forwarded-proto'] === 'https' || process.env.COOKIE_SECURE === '1';
|
|
357
|
+
res.setHeader('Set-Cookie', 'agentgui_token=' + encodeURIComponent(_pwd) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400' + (_https ? '; Secure' : ''));
|
|
358
|
+
} catch (_) {}
|
|
359
|
+
}
|
|
360
|
+
if (!_ok) {
|
|
361
|
+
// Penalize failed auth heavily in the rate bucket so a credential
|
|
362
|
+
// brute-force trips the 429 limiter long before it can guess.
|
|
363
|
+
rateLimitMap.set(clientIp, (rateLimitMap.get(clientIp) || 0) + 100);
|
|
364
|
+
res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="agentgui"' }); res.end('Unauthorized'); return;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const pathOnly = req.url.split('?')[0];
|
|
369
|
+
|
|
370
|
+
// Terminal RCE guard: the terminal surface spawns an interactive shell, so
|
|
371
|
+
// it is fail-closed by default. It is reachable ONLY when PASSWORD is set
|
|
372
|
+
// AND ENABLE_TERMINAL=1 is explicitly opted in. (Under the localhost-PASSWORD
|
|
373
|
+
// witness ENABLE_TERMINAL is unset, so the terminal is correctly disabled -
|
|
374
|
+
// it is not part of the witness.)
|
|
375
|
+
if (pathOnly.startsWith('/api/terminal/') || pathOnly.startsWith(BASE_URL + '/api/terminal/')) {
|
|
376
|
+
if (!process.env.PASSWORD || process.env.ENABLE_TERMINAL !== '1') {
|
|
377
|
+
sendJSON(req, res, 403, { error: 'terminal disabled (requires PASSWORD and ENABLE_TERMINAL=1)' });
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// CSRF guard on every state-changing method. Without PASSWORD the server
|
|
383
|
+
// is open and advertises a wildcard ACAO, so a cross-site page could POST
|
|
384
|
+
// a form at the mutation routes (rename/delete/mkdir/upload) on localhost.
|
|
385
|
+
// A simple cross-site form cannot set Sec-Fetch-Site:same-origin, send
|
|
386
|
+
// application/json, or attach custom headers - so: accept when the
|
|
387
|
+
// browser says same-origin/none (direct nav, same-origin fetch), when the
|
|
388
|
+
// body is declared JSON, or when an Authorization header rode along (a
|
|
389
|
+
// credentialed programmatic client). Reject the rest with 403.
|
|
390
|
+
if (req.method === 'POST' || req.method === 'PUT' || req.method === 'DELETE') {
|
|
391
|
+
const sfs = req.headers['sec-fetch-site'];
|
|
392
|
+
const ct = (req.headers['content-type'] || '').toLowerCase();
|
|
393
|
+
const sameSite = !sfs || sfs === 'same-origin' || sfs === 'none';
|
|
394
|
+
// Only application/json counts as a non-cross-site body now: a simple
|
|
395
|
+
// cross-site <form> can send only urlencoded/multipart/text-plain, and
|
|
396
|
+
// octet-stream / empty CT were too broad an escape (a no-CORS fetch can
|
|
397
|
+
// send octet-stream). The binary upload PUT still rides the same-origin
|
|
398
|
+
// SPA fetch (Sec-Fetch-Site: same-origin), so it passes via sameSite.
|
|
399
|
+
const jsonBody = ct.startsWith('application/json');
|
|
400
|
+
const authed = !!req.headers['authorization'];
|
|
401
|
+
// If an Origin header is present, its host MUST match the Host header -
|
|
402
|
+
// a cross-origin page's Origin will not, regardless of Sec-Fetch-Site.
|
|
403
|
+
let originOk = true;
|
|
404
|
+
const origin = req.headers['origin'];
|
|
405
|
+
if (origin) {
|
|
406
|
+
try { originOk = new URL(origin).host === req.headers['host']; }
|
|
407
|
+
catch { originOk = false; }
|
|
408
|
+
}
|
|
409
|
+
if (!originOk || (!sameSite && !jsonBody && !authed)) {
|
|
410
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
411
|
+
res.end(JSON.stringify({ error: 'cross-site request rejected' }));
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
if (pathOnly.startsWith(BASE_URL + '/api/upload/') || pathOnly.startsWith(BASE_URL + '/files/') || pathOnly.startsWith('/v1/history') || (BASE_URL && pathOnly.startsWith(BASE_URL + '/v1/history'))) return expressApp(req, res);
|
|
417
|
+
|
|
418
|
+
if (req.url === '/favicon.ico' || req.url === BASE_URL + '/favicon.ico') {
|
|
419
|
+
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" rx="20" fill="#3b82f6"/><text x="50" y="68" font-size="50" font-family="sans-serif" font-weight="bold" fill="white" text-anchor="middle">G</text></svg>';
|
|
420
|
+
res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=86400' });
|
|
421
|
+
res.end(svg); return;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// serve index.html at root directly (no redirect)
|
|
425
|
+
|
|
426
|
+
let routePath = req.url;
|
|
427
|
+
const _bareUrl = req.url.split('?')[0];
|
|
428
|
+
if (_bareUrl.startsWith(BASE_URL + '/')) { routePath = req.url.slice(BASE_URL.length); }
|
|
429
|
+
else if (_bareUrl === BASE_URL) { routePath = '/'; }
|
|
430
|
+
else if (_bareUrl.startsWith('/api/') || _bareUrl.startsWith('/js/') || _bareUrl.startsWith('/css/') ||
|
|
431
|
+
_bareUrl.startsWith('/vendor/') || _bareUrl.startsWith('/sync') || _bareUrl === '/' ||
|
|
432
|
+
_bareUrl === '/health' || _bareUrl.startsWith('/v1/') ||
|
|
433
|
+
_bareUrl.startsWith('/api/terminal/') ||
|
|
434
|
+
_bareUrl.startsWith('/conversations/')) { routePath = req.url; }
|
|
435
|
+
else { res.writeHead(404); res.end('Not found'); return; }
|
|
436
|
+
|
|
437
|
+
routePath = routePath || '/';
|
|
438
|
+
|
|
439
|
+
try {
|
|
440
|
+
const pathOnly = routePath.split('?')[0];
|
|
441
|
+
|
|
442
|
+
if ((pathOnly === '/api/health' || pathOnly === '/health') && req.method === 'GET') {
|
|
443
|
+
let dbStatus = { ok: true };
|
|
444
|
+
try { queries._db.prepare('SELECT 1').get(); } catch (e) { dbStatus = { ok: false, error: e.message }; }
|
|
445
|
+
const queueSizes = {};
|
|
446
|
+
for (const [k, v] of messageQueues) queueSizes[k] = v.length;
|
|
447
|
+
const _body = {
|
|
448
|
+
status: 'ok', version: PKG_VERSION, uptime: process.uptime(), agents: discoveredAgents.length,
|
|
449
|
+
activeExecutions: activeExecutions.size, wsClients: getWss()?.clients?.size ?? 0,
|
|
450
|
+
acp: getACPStatus(), db: dbStatus, queueSizes,
|
|
451
|
+
// Surfaces the console-only CORS_ORIGIN=*+no-PASSWORD warning (above)
|
|
452
|
+
// as a fact the GUI settings panel can render a persistent banner
|
|
453
|
+
// from - an operator not tailing logs otherwise never sees the risk.
|
|
454
|
+
corsWildcardOpen: process.env.CORS_ORIGIN === '*' && !process.env.PASSWORD,
|
|
455
|
+
};
|
|
456
|
+
// Host-internal facts (memory, filesystem paths) are exposed only to an
|
|
457
|
+
// authenticated caller, never on the unauthenticated health-probe bypass.
|
|
458
|
+
if (!_healthExempt) {
|
|
459
|
+
_body.memory = process.memoryUsage();
|
|
460
|
+
_body.projectsDir = process.env.CLAUDE_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects');
|
|
461
|
+
_body.allowRoots = fsAllowRoots();
|
|
462
|
+
}
|
|
463
|
+
sendJSON(req, res, 200, _body);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Existence/shape probe for a proposed chat working directory, confined
|
|
468
|
+
// to the same allowlist as the Files surface (an unconfined stat would be
|
|
469
|
+
// a filesystem oracle). Returns {ok, dir} or a 403/404 with plain copy.
|
|
470
|
+
if (routePath.startsWith('/api/stat') && req.method === 'GET') {
|
|
471
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/stat');
|
|
472
|
+
const conf = confineToRoots(decodedPath, fsAllowRoots());
|
|
473
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: conf.reason }); return; }
|
|
474
|
+
try {
|
|
475
|
+
const st = fs.statSync(conf.realPath);
|
|
476
|
+
sendJSON(req, res, 200, { ok: true, dir: st.isDirectory(), path: conf.realPath });
|
|
477
|
+
} catch (err) {
|
|
478
|
+
sendJSON(req, res, err.code === 'ENOENT' ? 404 : 403, { error: safeErrMsg(err) });
|
|
479
|
+
}
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// Terminal sessions - gated by the Basic-auth check at the top of this handler.
|
|
484
|
+
// Never expose these routes without PASSWORD set.
|
|
485
|
+
if (pathOnly === '/api/terminal/sessions' && req.method === 'GET') {
|
|
486
|
+
sendJSON(req, res, 200, term.listSessions()); return;
|
|
487
|
+
}
|
|
488
|
+
if (pathOnly === '/api/terminal/sessions' && req.method === 'POST') {
|
|
489
|
+
let body = ''; for await (const c of req) body += c;
|
|
490
|
+
let p = {}; try { p = body ? JSON.parse(body) : {}; } catch {}
|
|
491
|
+
// Never honour a client-supplied shell or env - that would be a direct
|
|
492
|
+
// command/arg injection into the spawned process. Only geometry + cwd.
|
|
493
|
+
// Confine cwd to allowed roots; fall back to STARTUP_CWD on failure.
|
|
494
|
+
let termCwd = process.env.STARTUP_CWD || process.cwd();
|
|
495
|
+
if (p.cwd) {
|
|
496
|
+
const cwdConf = confineToRoots(p.cwd, fsAllowRoots());
|
|
497
|
+
if (cwdConf.ok) termCwd = cwdConf.realPath;
|
|
498
|
+
}
|
|
499
|
+
const s = term.createSession({ cwd: termCwd, cols: p.cols, rows: p.rows });
|
|
500
|
+
sendJSON(req, res, 200, { sid: s.sid, kind: s.kind, shell: s.shell, cwd: s.cwd, cols: s.cols, rows: s.rows, pid: s.proc.pid });
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
const termMatch = pathOnly.match(/^\/api\/terminal\/sessions\/([0-9a-f]+)$/);
|
|
504
|
+
if (termMatch && req.method === 'GET') {
|
|
505
|
+
const s = term.getSession(termMatch[1]);
|
|
506
|
+
if (!s) { sendJSON(req, res, 404, { error: 'session not found' }); return; }
|
|
507
|
+
sendJSON(req, res, 200, { sid: s.sid, kind: s.kind, shell: s.shell, cwd: s.cwd, cols: s.cols, rows: s.rows, pid: s.proc.pid, clients: s.clients.size });
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (termMatch && req.method === 'DELETE') {
|
|
511
|
+
const ok = term.closeSession(termMatch[1]);
|
|
512
|
+
sendJSON(req, res, ok ? 200 : 404, { ok }); return;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// Legacy REST handlers removed. History served by ccsniff at /v1/history/*.
|
|
516
|
+
for (const key of Object.keys(routes)) {
|
|
517
|
+
try {
|
|
518
|
+
const h = routes[key]?._match?.(req.method, pathOnly);
|
|
519
|
+
if (h) { await h(req, res); return; }
|
|
520
|
+
} catch (_) {}
|
|
521
|
+
}
|
|
522
|
+
// Directory listing for the Files / folder-browser view (mirrors fsbrowse
|
|
523
|
+
// /api/list). Confined to an allowlist root exactly like /api/image - the
|
|
524
|
+
// normalize-then-prefix-check is the real guard (a `..` test after
|
|
525
|
+
// path.normalize is a no-op). Returns {path, segments, entries} so the kit
|
|
526
|
+
// FileGrid + BreadcrumbPath render directly. Allowed roots default to the
|
|
527
|
+
// server cwd + Claude projects dir; widen via FS_ROOTS (path-separated).
|
|
528
|
+
if (routePath.startsWith('/api/list')) {
|
|
529
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'dir', '/api/list');
|
|
530
|
+
const allowRoots = fsAllowRoots();
|
|
531
|
+
// Empty path = the first allow-root (a sane default landing dir).
|
|
532
|
+
const reqPath = !decodedPath ? allowRoots[0] : decodedPath;
|
|
533
|
+
const conf = confineToRoots(reqPath, allowRoots);
|
|
534
|
+
if (!conf.ok) {
|
|
535
|
+
const code = conf.reason === 'not found' ? 404 : 403;
|
|
536
|
+
sendJSON(req, res, code, { error: 'forbidden: ' + conf.reason }); return;
|
|
537
|
+
}
|
|
538
|
+
// Use the symlink-resolved real path for all reads.
|
|
539
|
+
const normalizedPath = conf.realPath;
|
|
540
|
+
try {
|
|
541
|
+
const st = fs.statSync(normalizedPath);
|
|
542
|
+
if (!st.isDirectory()) { sendJSON(req, res, 400, { error: 'not a directory' }); return; }
|
|
543
|
+
// Classify by extension into the kit's data-file-type buckets so
|
|
544
|
+
// FileGrid renders the right rail/icon. dir/symlink come from stat.
|
|
545
|
+
const EXT_TYPE = {
|
|
546
|
+
image: ['png','jpg','jpeg','gif','webp','svg','bmp','ico','avif'],
|
|
547
|
+
video: ['mp4','webm','mov','mkv','avi','m4v'],
|
|
548
|
+
audio: ['mp3','wav','ogg','flac','m4a','aac'],
|
|
549
|
+
code: ['js','mjs','cjs','ts','tsx','jsx','rs','go','py','rb','java','c','cpp','h','hpp','cs','php','sh','css','html','json','yml','yaml','toml','sql'],
|
|
550
|
+
text: ['txt','md','log','csv','env'],
|
|
551
|
+
archive: ['zip','tar','gz','tgz','rar','7z','bz2','xz'],
|
|
552
|
+
document: ['pdf','doc','docx','xls','xlsx','ppt','pptx','odt'],
|
|
553
|
+
};
|
|
554
|
+
const typeFor = (name, dirent) => {
|
|
555
|
+
if (dirent.isSymbolicLink()) return 'symlink';
|
|
556
|
+
if (dirent.isDirectory()) return 'dir';
|
|
557
|
+
const ext = path.extname(name).slice(1).toLowerCase();
|
|
558
|
+
for (const [t, exts] of Object.entries(EXT_TYPE)) if (exts.includes(ext)) return t;
|
|
559
|
+
return 'other';
|
|
560
|
+
};
|
|
561
|
+
const dirents = fs.readdirSync(normalizedPath, { withFileTypes: true }).filter((d) => !SECRET_RE.test(d.name));
|
|
562
|
+
const entries = dirents.map((d) => {
|
|
563
|
+
const full = path.join(normalizedPath, d.name);
|
|
564
|
+
let size = null, modified = null, permissions;
|
|
565
|
+
try {
|
|
566
|
+
const s = fs.statSync(full); size = s.isDirectory() ? null : s.size; modified = s.mtime.toISOString();
|
|
567
|
+
// Per-entry permission probe (mirrors fsbrowse checkPermissions) so
|
|
568
|
+
// the row reads honestly (read-only / no access) instead of a silent
|
|
569
|
+
// size:null on a stat failure. A stat success means at least read.
|
|
570
|
+
const perms = ['read'];
|
|
571
|
+
try { fs.accessSync(full, fs.constants.W_OK); perms.push('write'); } catch (_) {}
|
|
572
|
+
permissions = perms;
|
|
573
|
+
} catch (e) {
|
|
574
|
+
// Could not stat (commonly EACCES): mark no-access so the client
|
|
575
|
+
// disables open + shows the tag, rather than failing silently.
|
|
576
|
+
permissions = e && e.code === 'EACCES' ? 'EACCES' : [];
|
|
577
|
+
}
|
|
578
|
+
return { name: d.name, type: typeFor(d.name, d), size, modified, path: full, permissions };
|
|
579
|
+
}).sort((a, b) => (a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) || a.name.localeCompare(b.name));
|
|
580
|
+
// Breadcrumb segments from the absolute path (drive/root aware).
|
|
581
|
+
const segments = normalizedPath.split(/[\\\/]+/).filter(Boolean);
|
|
582
|
+
sendJSON(req, res, 200, { path: normalizedPath, segments, entries, roots: allowRoots });
|
|
583
|
+
} catch (err) {
|
|
584
|
+
const code = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
|
|
585
|
+
sendJSON(req, res, code, { error: safeErrMsg(err) });
|
|
586
|
+
}
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// Raw file bytes for the Files preview pane. Confined to the SAME
|
|
591
|
+
// allowlist roots as /api/list (server cwd + Claude projects dir, widened
|
|
592
|
+
// via FS_ROOTS). Same normalize-then-prefix-check guard. Capped at 512KB
|
|
593
|
+
// and limited to reasonable text/code/image types so this is never a
|
|
594
|
+
// generic arbitrary-file reader. Images are served via /api/image; this
|
|
595
|
+
// returns text/* with utf-8.
|
|
596
|
+
if (routePath.startsWith('/api/file/') || routePath.startsWith('/api/file?')) {
|
|
597
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/file/');
|
|
598
|
+
const allowRoots = fsAllowRoots();
|
|
599
|
+
const conf = confineToRoots(decodedPath, allowRoots);
|
|
600
|
+
if (!conf.ok) { res.writeHead(conf.reason === 'not found' ? 404 : 403); res.end('Forbidden'); return; }
|
|
601
|
+
const normalizedPath = conf.realPath;
|
|
602
|
+
// Block secret-bearing files regardless of root: dotfiles, env/key/cert
|
|
603
|
+
// material, and credential stores must never be readable through the
|
|
604
|
+
// Files preview even when they sit inside an allowed root.
|
|
605
|
+
const base = path.basename(normalizedPath);
|
|
606
|
+
if (SECRET_RE.test(base)) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
607
|
+
// Only known text/code extensions (images go through /api/image). An
|
|
608
|
+
// unknown/binary extension is rejected, never served as octet-stream.
|
|
609
|
+
// env/conf/cfg/ini are dropped - they commonly carry secrets.
|
|
610
|
+
const TEXT_EXTS = new Set([
|
|
611
|
+
'js','mjs','cjs','ts','tsx','jsx','rs','go','py','rb','java','c','cpp','h','hpp','cs','php','sh','css','html','json','yml','yaml','toml','sql',
|
|
612
|
+
'txt','md','log','csv','xml','gitignore','dockerfile','svg',
|
|
613
|
+
]);
|
|
614
|
+
const ext = path.extname(normalizedPath).slice(1).toLowerCase()
|
|
615
|
+
|| path.basename(normalizedPath).toLowerCase();
|
|
616
|
+
if (!TEXT_EXTS.has(ext)) { res.writeHead(403); res.end('Forbidden: unsupported type'); return; }
|
|
617
|
+
try {
|
|
618
|
+
const st = fs.statSync(normalizedPath);
|
|
619
|
+
if (!st.isFile()) { res.writeHead(400); res.end('Not a file'); return; }
|
|
620
|
+
const MAX = 512 * 1024;
|
|
621
|
+
const fd = fs.openSync(normalizedPath, 'r');
|
|
622
|
+
const len = Math.min(st.size, MAX);
|
|
623
|
+
const buf = Buffer.alloc(len);
|
|
624
|
+
fs.readSync(fd, buf, 0, len, 0);
|
|
625
|
+
fs.closeSync(fd);
|
|
626
|
+
res.writeHead(200, {
|
|
627
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
628
|
+
'Cache-Control': 'no-cache',
|
|
629
|
+
'X-File-Truncated': st.size > MAX ? '1' : '0',
|
|
630
|
+
});
|
|
631
|
+
res.end(buf);
|
|
632
|
+
} catch (err) {
|
|
633
|
+
const code = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
|
|
634
|
+
res.writeHead(code); res.end(safeErrMsg(err));
|
|
635
|
+
}
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// Confined raw-bytes download (any type) with an attachment disposition,
|
|
640
|
+
// so the Files view can offer download on a row. Same allowlist + realpath
|
|
641
|
+
// confinement as /api/file and /api/image - never a generic file reader.
|
|
642
|
+
if (routePath.startsWith('/api/download/') || routePath.startsWith('/api/download?')) {
|
|
643
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/download/');
|
|
644
|
+
const allowRoots = fsAllowRoots();
|
|
645
|
+
const conf = confineToRoots(decodedPath, allowRoots);
|
|
646
|
+
if (!conf.ok) { res.writeHead(conf.reason === 'not found' ? 404 : 403); res.end('Forbidden'); return; }
|
|
647
|
+
const normalizedPath = conf.realPath;
|
|
648
|
+
// Same secret-name block as /api/file: a download must not exfiltrate
|
|
649
|
+
// .env/.pem/.key/credential material just because it streams bytes.
|
|
650
|
+
if (SECRET_RE.test(path.basename(normalizedPath))) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
651
|
+
try {
|
|
652
|
+
const st = fs.statSync(normalizedPath);
|
|
653
|
+
if (!st.isFile()) { res.writeHead(400); res.end('Not a file'); return; }
|
|
654
|
+
const MAX = 50 * 1024 * 1024; // 50MB cap so a download can't exhaust memory
|
|
655
|
+
if (st.size > MAX) { res.writeHead(413); res.end('File too large to download'); return; }
|
|
656
|
+
const base = path.basename(normalizedPath);
|
|
657
|
+
const asciiName = base.replace(/[\\"\r\n]/g, '').replace(/[^\x20-\x7e]/g, '_');
|
|
658
|
+
res.writeHead(200, {
|
|
659
|
+
'Content-Type': 'application/octet-stream',
|
|
660
|
+
'Content-Disposition': 'attachment; filename="' + asciiName + '"; filename*=UTF-8\'\'' + encodeURIComponent(base),
|
|
661
|
+
'Content-Length': String(st.size),
|
|
662
|
+
'Cache-Control': 'no-cache',
|
|
663
|
+
});
|
|
664
|
+
const rs = fs.createReadStream(normalizedPath);
|
|
665
|
+
rs.on('error', (streamErr) => { if (!res.writableEnded) res.destroy(streamErr); });
|
|
666
|
+
rs.pipe(res);
|
|
667
|
+
} catch (err) {
|
|
668
|
+
const code = err && err.code === 'ENOENT' ? 404 : (err && err.code === 'EACCES' ? 403 : 400);
|
|
669
|
+
res.writeHead(code); res.end(safeErrMsg(err));
|
|
670
|
+
}
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// --- File mutations ----------------------------------------------------
|
|
675
|
+
// The Files surface is a real manager (fsbrowse-grade): rename, delete,
|
|
676
|
+
// mkdir, upload. Every route re-confines via confineToRoots (realpath, so
|
|
677
|
+
// a symlink inside a root cannot point a mutation outside it), refuses
|
|
678
|
+
// the roots themselves as targets, and sanitizes any NEW name to a single
|
|
679
|
+
// path component (sanitizeEntryName). All are POST/PUT-only with JSON or
|
|
680
|
+
// raw-byte bodies; errors map to plain machine codes the client renders
|
|
681
|
+
// as human copy.
|
|
682
|
+
|
|
683
|
+
// POST /api/rename {path, newName} -> {ok, path}
|
|
684
|
+
if (routePath.split('?')[0] === '/api/rename' && req.method === 'POST') {
|
|
685
|
+
let body;
|
|
686
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
687
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
688
|
+
const allowRoots = fsAllowRoots();
|
|
689
|
+
const conf = confineToRoots(String(body.path || ''), allowRoots);
|
|
690
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
691
|
+
if (isAllowRoot(conf.realPath, allowRoots)) { sendJSON(req, res, 403, { error: 'forbidden: cannot rename an allowed root' }); return; }
|
|
692
|
+
const newName = sanitizeEntryName(body.newName);
|
|
693
|
+
if (!newName) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
694
|
+
if (SECRET_RE.test(newName)) { sendJSON(req, res, 403, { error: 'forbidden: secret/dotfile name' }); return; }
|
|
695
|
+
const target = path.join(path.dirname(conf.realPath), newName);
|
|
696
|
+
// The target stays in the same (already-confined) directory by
|
|
697
|
+
// construction, but re-check anyway so the invariant is local.
|
|
698
|
+
const tConf = confineToRoots(path.dirname(target), allowRoots);
|
|
699
|
+
if (!tConf.ok) { sendJSON(req, res, 403, { error: 'forbidden: target outside allowed roots' }); return; }
|
|
700
|
+
if (fs.existsSync(target)) { sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return; }
|
|
701
|
+
try { fs.renameSync(conf.realPath, target); sendJSON(req, res, 200, { ok: true, path: target }); }
|
|
702
|
+
catch (err) { sendJSON(req, res, err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400, { error: safeErrMsg(err) }); }
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// POST /api/move {path, destDir, overwrite?} -> {ok, path}. Moves an
|
|
707
|
+
// entry into another directory; BOTH endpoints re-confine via realpath.
|
|
708
|
+
// Refuses: a root as the source, a directory moved into itself or its
|
|
709
|
+
// own subtree, and an existing target unless overwrite:true (and never
|
|
710
|
+
// overwrites a directory).
|
|
711
|
+
if (routePath.split('?')[0] === '/api/move' && req.method === 'POST') {
|
|
712
|
+
let body;
|
|
713
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
714
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
715
|
+
const allowRoots = fsAllowRoots();
|
|
716
|
+
const conf = confineToRoots(String(body.path || ''), allowRoots);
|
|
717
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
718
|
+
if (isAllowRoot(conf.realPath, allowRoots)) { sendJSON(req, res, 403, { error: 'forbidden: cannot move an allowed root' }); return; }
|
|
719
|
+
const dConf = confineToRoots(String(body.destDir || ''), allowRoots);
|
|
720
|
+
if (!dConf.ok) { sendJSON(req, res, dConf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + dConf.reason }); return; }
|
|
721
|
+
let destIsDir = false;
|
|
722
|
+
try { destIsDir = fs.statSync(dConf.realPath).isDirectory(); } catch {}
|
|
723
|
+
if (!destIsDir) { sendJSON(req, res, 400, { error: 'destination is not a directory' }); return; }
|
|
724
|
+
const name = sanitizeEntryName(path.basename(conf.realPath));
|
|
725
|
+
if (!name) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
726
|
+
// A directory must never move into itself or its own subtree.
|
|
727
|
+
const srcPrefix = conf.realPath + path.sep;
|
|
728
|
+
if (dConf.realPath === conf.realPath || dConf.realPath.startsWith(srcPrefix)) {
|
|
729
|
+
sendJSON(req, res, 400, { error: 'cannot move a folder into itself' }); return;
|
|
730
|
+
}
|
|
731
|
+
const target = path.join(dConf.realPath, name);
|
|
732
|
+
if (target === conf.realPath) { sendJSON(req, res, 200, { ok: true, path: target }); return; }
|
|
733
|
+
if (fs.existsSync(target)) {
|
|
734
|
+
let targetIsDir = false;
|
|
735
|
+
try { targetIsDir = fs.lstatSync(target).isDirectory(); } catch {}
|
|
736
|
+
if (targetIsDir || body.overwrite !== true) {
|
|
737
|
+
sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
try { fs.renameSync(conf.realPath, target); sendJSON(req, res, 200, { ok: true, path: target }); }
|
|
741
|
+
catch (err) {
|
|
742
|
+
const code = err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400;
|
|
743
|
+
sendJSON(req, res, code, { error: err.code === 'EXDEV' ? 'cannot move across drives' : err.message });
|
|
744
|
+
}
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// POST /api/delete {path, recursive?} -> {ok}. Deleting a non-empty dir
|
|
749
|
+
// requires recursive:true (the client confirms first).
|
|
750
|
+
if (routePath.split('?')[0] === '/api/delete' && req.method === 'POST') {
|
|
751
|
+
let body;
|
|
752
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
753
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
754
|
+
const allowRoots = fsAllowRoots();
|
|
755
|
+
const conf = confineToRoots(String(body.path || ''), allowRoots);
|
|
756
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
757
|
+
if (isAllowRoot(conf.realPath, allowRoots)) { sendJSON(req, res, 403, { error: 'forbidden: cannot delete an allowed root' }); return; }
|
|
758
|
+
try {
|
|
759
|
+
const st = fs.lstatSync(conf.realPath);
|
|
760
|
+
// Soft-delete: move into a confined per-root .agentgui-trash/ instead
|
|
761
|
+
// of unlinking, so the only safety net isn't confirm-before (the
|
|
762
|
+
// pre-existing ConfirmDialog) but also undo-after, matching an
|
|
763
|
+
// fsbrowse-grade file manager. A non-empty directory without
|
|
764
|
+
// recursive=true still throws ENOTEMPTY BEFORE any move happens
|
|
765
|
+
// (checked via a dry probe) to keep that existing guard's semantics.
|
|
766
|
+
if (st.isDirectory() && body.recursive !== true) {
|
|
767
|
+
const dryEntries = fs.readdirSync(conf.realPath);
|
|
768
|
+
if (dryEntries.length) { sendJSON(req, res, 409, { error: 'directory is not empty' }); return; }
|
|
769
|
+
}
|
|
770
|
+
const trashInfo = moveToTrash(conf.realPath, allowRoots);
|
|
771
|
+
sendJSON(req, res, 200, { ok: true, trashId: trashInfo.trashId });
|
|
772
|
+
} catch (err) {
|
|
773
|
+
const code = err.code === 'ENOTEMPTY' ? 409 : (err.code === 'EACCES' || err.code === 'EPERM' ? 403 : (err.code === 'ENOENT' ? 404 : 400));
|
|
774
|
+
sendJSON(req, res, code, { error: err.code === 'ENOTEMPTY' ? 'directory is not empty' : err.message });
|
|
775
|
+
}
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// POST /api/restore {trashId} -> {ok, path}. Undoes a /api/delete within
|
|
780
|
+
// its retention window (trashRetentionMs, default 10 minutes) by moving
|
|
781
|
+
// the entry back from .agentgui-trash/ to its original confined path.
|
|
782
|
+
if (routePath.split('?')[0] === '/api/restore' && req.method === 'POST') {
|
|
783
|
+
let body;
|
|
784
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
785
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
786
|
+
try {
|
|
787
|
+
const restored = restoreFromTrash(String(body.trashId || ''), fsAllowRoots());
|
|
788
|
+
sendJSON(req, res, 200, { ok: true, path: restored.path });
|
|
789
|
+
} catch (err) {
|
|
790
|
+
sendJSON(req, res, err.code === 'NOT_FOUND' ? 404 : (err.code === 'CONFLICT' ? 409 : 400), { error: err.message });
|
|
791
|
+
}
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// POST /api/mkdir {dir, name} -> {ok, path}. dir must exist inside roots.
|
|
796
|
+
if (routePath.split('?')[0] === '/api/mkdir' && req.method === 'POST') {
|
|
797
|
+
let body;
|
|
798
|
+
try { body = JSON.parse((await readBody(req, 64 * 1024)).toString('utf8') || '{}'); }
|
|
799
|
+
catch (e) { sendJSON(req, res, e.code === 'TOO_LARGE' ? 413 : 400, { error: 'bad request body' }); return; }
|
|
800
|
+
const allowRoots = fsAllowRoots();
|
|
801
|
+
const conf = confineToRoots(String(body.dir || ''), allowRoots);
|
|
802
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
803
|
+
const name = sanitizeEntryName(body.name);
|
|
804
|
+
if (!name) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
805
|
+
if (SECRET_RE.test(name)) { sendJSON(req, res, 403, { error: 'forbidden: secret/dotfile name' }); return; }
|
|
806
|
+
const target = path.join(conf.realPath, name);
|
|
807
|
+
if (fs.existsSync(target)) { sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return; }
|
|
808
|
+
try { fs.mkdirSync(target); sendJSON(req, res, 200, { ok: true, path: target }); }
|
|
809
|
+
catch (err) { sendJSON(req, res, err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400, { error: err.message }); }
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// PUT /api/upload-file?dir=<enc>&name=<enc> with raw file bytes as the
|
|
814
|
+
// body (no multipart dependency; the client sends fetch(file)). 50MB cap,
|
|
815
|
+
// never overwrites unless ?overwrite=1. Distinct path from the legacy
|
|
816
|
+
// express-mounted /api/upload/:conversationId.
|
|
817
|
+
if (routePath.split('?')[0] === '/api/upload-file' && req.method === 'PUT') {
|
|
818
|
+
let qs;
|
|
819
|
+
try { qs = new URL(req.url, 'http://localhost').searchParams; } catch { qs = new URLSearchParams(); }
|
|
820
|
+
// Require Content-Length header: rejects chunked or missing-length requests
|
|
821
|
+
// that could claim any size. Pre-validates the announced size before streaming.
|
|
822
|
+
const contentLength = req.headers['content-length'];
|
|
823
|
+
if (!contentLength) {
|
|
824
|
+
sendJSON(req, res, 411, { error: 'length required' }); return;
|
|
825
|
+
}
|
|
826
|
+
const MAX_UPLOAD = 50 * 1024 * 1024;
|
|
827
|
+
const len = parseInt(contentLength, 10);
|
|
828
|
+
if (isNaN(len) || len < 0 || len > MAX_UPLOAD) {
|
|
829
|
+
sendJSON(req, res, 413, { error: `file too large (max ${MAX_UPLOAD} bytes)` }); return;
|
|
830
|
+
}
|
|
831
|
+
const allowRoots = fsAllowRoots();
|
|
832
|
+
const conf = confineToRoots(qs.get('dir') || '', allowRoots);
|
|
833
|
+
if (!conf.ok) { sendJSON(req, res, conf.reason === 'not found' ? 404 : 403, { error: 'forbidden: ' + conf.reason }); return; }
|
|
834
|
+
const name = sanitizeEntryName(qs.get('name'));
|
|
835
|
+
if (!name) { sendJSON(req, res, 400, { error: 'invalid name' }); return; }
|
|
836
|
+
if (SECRET_RE.test(name)) { sendJSON(req, res, 403, { error: 'forbidden: secret/dotfile name' }); return; }
|
|
837
|
+
const target = path.join(conf.realPath, name);
|
|
838
|
+
if (fs.existsSync(target) && qs.get('overwrite') !== '1') { sendJSON(req, res, 409, { error: 'a file with that name already exists' }); return; }
|
|
839
|
+
// Stream the upload body to a temp file to keep memory constant and
|
|
840
|
+
// avoid blocking the event loop with a large synchronous writeFileSync.
|
|
841
|
+
const tmpPath = target + '.tmp.' + crypto.randomBytes(6).toString('hex');
|
|
842
|
+
try {
|
|
843
|
+
await new Promise((resolve, reject) => {
|
|
844
|
+
const ws = fs.createWriteStream(tmpPath);
|
|
845
|
+
let total = 0;
|
|
846
|
+
ws.on('error', reject);
|
|
847
|
+
req.on('error', reject);
|
|
848
|
+
req.on('data', (chunk) => {
|
|
849
|
+
total += chunk.length;
|
|
850
|
+
if (total > MAX_UPLOAD) {
|
|
851
|
+
ws.destroy();
|
|
852
|
+
req.destroy();
|
|
853
|
+
const e = new Error('file too large (50MB cap)'); e.code = 'TOO_LARGE';
|
|
854
|
+
reject(e); return;
|
|
855
|
+
}
|
|
856
|
+
ws.write(chunk);
|
|
857
|
+
});
|
|
858
|
+
req.on('end', () => ws.end());
|
|
859
|
+
ws.on('finish', () => resolve(total));
|
|
860
|
+
});
|
|
861
|
+
fs.renameSync(tmpPath, target);
|
|
862
|
+
const uploadedSize = fs.statSync(target).size;
|
|
863
|
+
sendJSON(req, res, 200, { ok: true, path: target, size: uploadedSize });
|
|
864
|
+
} catch (err) {
|
|
865
|
+
try { fs.unlinkSync(tmpPath); } catch (_) {}
|
|
866
|
+
if (err.code === 'TOO_LARGE') { sendJSON(req, res, 413, { error: 'file too large (50MB cap)' }); return; }
|
|
867
|
+
sendJSON(req, res, err.code === 'EACCES' || err.code === 'EPERM' ? 403 : 400, { error: 'upload failed' });
|
|
868
|
+
}
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
if (routePath.startsWith('/api/image/') || routePath.startsWith('/api/image?')) {
|
|
873
|
+
const decodedPath = resolveConfinedPath(req, routePath, 'path', '/api/image/');
|
|
874
|
+
// Confine reads to an allowlist root. Without this the route is an
|
|
875
|
+
// arbitrary-file-read of any image-extensioned path on the host (the
|
|
876
|
+
// prior `includes('..')` guard is a no-op after path.normalize resolves
|
|
877
|
+
// the segments). Allowed roots: the Claude projects dir (history images)
|
|
878
|
+
// only; add more via IMAGE_ROOTS (path-separated). The user home is NOT
|
|
879
|
+
// a default root - it covers ~/.ssh, ~/.aws, dotfiles etc., so an image
|
|
880
|
+
// route reaching all of home is a broad read of anything image-shaped.
|
|
881
|
+
// confineToRoots also realpath-resolves so a symlink inside a root can't
|
|
882
|
+
// point an image read at an out-of-root file.
|
|
883
|
+
const allowRoots = [
|
|
884
|
+
process.env.CLAUDE_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects'),
|
|
885
|
+
...(process.env.IMAGE_ROOTS ? process.env.IMAGE_ROOTS.split(path.delimiter) : []),
|
|
886
|
+
].map(r => path.normalize(r));
|
|
887
|
+
const conf = confineToRoots(decodedPath, allowRoots);
|
|
888
|
+
if (!conf.ok) { res.writeHead(conf.reason === 'not found' ? 404 : 403); res.end(conf.reason === 'not found' ? 'Not found' : 'Forbidden'); return; }
|
|
889
|
+
const normalizedPath = conf.realPath;
|
|
890
|
+
try {
|
|
891
|
+
const ext = path.extname(normalizedPath).toLowerCase();
|
|
892
|
+
const mimeTypes = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
|
|
893
|
+
// SVG is intentionally excluded: browsers render SVG as a live document
|
|
894
|
+
// in the app's origin, so an agent-written SVG with a <script src=CDN>
|
|
895
|
+
// would execute in the agentgui origin (CSP allows unpkg/jsdelivr).
|
|
896
|
+
// Files preview uses /api/file/download (attachment) for SVG.
|
|
897
|
+
const contentType = mimeTypes[ext];
|
|
898
|
+
if (!contentType) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
899
|
+
const imgSt = fs.statSync(normalizedPath);
|
|
900
|
+
const IMG_MAX = 20 * 1024 * 1024; // 20MB hard cap
|
|
901
|
+
if (imgSt.size > IMG_MAX) { res.writeHead(413); res.end('Image too large'); return; }
|
|
902
|
+
// Always stream to avoid blocking the event loop on large synchronous reads.
|
|
903
|
+
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-cache', 'Content-Length': String(imgSt.size) });
|
|
904
|
+
const imgRs = fs.createReadStream(normalizedPath);
|
|
905
|
+
imgRs.on('error', (streamErr) => { if (!res.writableEnded) res.destroy(streamErr); });
|
|
906
|
+
imgRs.pipe(res);
|
|
907
|
+
} catch (err) { sendJSON(req, res, 400, { error: 'cannot read image' }); }
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
if (pathOnly.match(/^\/conversations\/[^\/]+$/)) { serveFile(path.join(staticDir, 'index.html'), res, req, cspNonce); return; }
|
|
912
|
+
|
|
913
|
+
const routePathBare = routePath.split('?')[0];
|
|
914
|
+
let filePath = routePathBare === '/' ? '/index.html' : routePathBare;
|
|
915
|
+
filePath = path.join(staticDir, filePath);
|
|
916
|
+
const normalizedPath = path.normalize(filePath);
|
|
917
|
+
if (!normalizedPath.startsWith(staticDir)) { res.writeHead(403); res.end('Forbidden'); return; }
|
|
918
|
+
|
|
919
|
+
fs.stat(filePath, (err, stats) => {
|
|
920
|
+
if (err) { res.writeHead(404); res.end('Not found'); return; }
|
|
921
|
+
if (stats.isDirectory()) {
|
|
922
|
+
filePath = path.join(filePath, 'index.html');
|
|
923
|
+
fs.stat(filePath, (err2) => { if (err2) { res.writeHead(404); res.end('Not found'); return; } serveFile(filePath, res, req, cspNonce); });
|
|
924
|
+
} else { serveFile(filePath, res, req, cspNonce); }
|
|
925
|
+
});
|
|
926
|
+
} catch (e) {
|
|
927
|
+
console.error('Server error:', maskToken(e.message), e.stack, '| path:', maskToken(req.url.split('?')[0]));
|
|
928
|
+
sendJSON(req, res, 500, { error: 'internal server error' });
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
}
|