跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

macos-project-access.m

502 行 · 19.0 KB历史下载
1// Per-user guest application. macOS grants only the project selected in the
2// native Open panel. Terminal and editor children inherit that user selection.
3#import <AppKit/AppKit.h>
4#import <fcntl.h>
5#import <poll.h>
6#import <signal.h>
7#import <spawn.h>
8#import <sys/file.h>
9#import <sys/ioctl.h>
10#import <sys/mount.h>
11#import <sys/socket.h>
12#import <sys/stat.h>
13#import <sys/un.h>
14#import <sys/wait.h>
15#import <termios.h>
16#import <unistd.h>
17
18extern char **environ;
19static NSString *socketPath(void) {
20 return [NSHomeDirectory()
21 stringByAppendingPathComponent:@"Library/Application Support/Cage/project-terminal.sock"];
22}
23static BOOL addressForSocket(struct sockaddr_un *address) {
24 const char *p = socketPath().fileSystemRepresentation;
25 memset(address, 0, sizeof(*address));
26 address->sun_family = AF_UNIX;
27 return strlcpy(address->sun_path, p, sizeof(address->sun_path)) < sizeof(address->sun_path);
28}
29static BOOL writeAll(int fd, const void *data, size_t count) {
30 const char *p = data;
31 while (count) {
32 ssize_t n = write(fd, p, count);
33 if (n < 0 && errno == EINTR)
34 continue;
35 if (n <= 0)
36 return NO;
37 p += n;
38 count -= n;
39 }
40 return YES;
41}
42static void reply(int fd, const char *message) { writeAll(fd, message, strlen(message)); }
43static NSString *mountID(NSString *project) {
44 if (![project isKindOfClass:NSString.class] || ![project.stringByStandardizingPath isEqual:project])
45 return nil;
46 NSString *base = [NSHomeDirectory() stringByAppendingPathComponent:@"Cage/Projects"];
47 NSString *leaf = project.lastPathComponent;
48 if (![project.stringByDeletingLastPathComponent isEqual:base] || leaf.length != 24 ||
49 [leaf rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"]
50 .invertedSet]
51 .location != NSNotFound)
52 return nil;
53 struct statfs fs;
54 if (statfs(project.fileSystemRepresentation, &fs) ||
55 strcmp(fs.f_mntonname, project.fileSystemRepresentation) || strcmp(fs.f_fstypename, "macfuse") ||
56 fs.f_owner != getuid() || (fs.f_flags & (MNT_NOSUID | MNT_NODEV)) != (MNT_NOSUID | MNT_NODEV))
57 return nil;
58 return [NSString stringWithUTF8String:fs.f_mntfromname];
59}
60
61@interface ProjectAccess : NSObject <NSApplicationDelegate, NSOpenSavePanelDelegate>
62@end
63@implementation ProjectAccess {
64 NSMutableDictionary<NSString *, NSURL *> *_scopes;
65 NSMutableDictionary<NSString *, NSString *> *_ready;
66 NSString *_requesting;
67 NSString *_nonce;
68 NSOpenPanel *_panel;
69 NSMutableDictionary<NSString *, NSDate *> *_declined;
70}
71- (void)applicationDidFinishLaunching:(NSNotification *)note {
72 _scopes = [NSMutableDictionary dictionary];
73 _ready = [NSMutableDictionary dictionary];
74 _declined = [NSMutableDictionary dictionary];
75 dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
76 [self serve];
77 });
78}
79// These state and UI methods run on the main thread.
80- (BOOL)restore:(NSString *)project {
81 if (_scopes[project])
82 return YES;
83 NSData *saved = [[NSUserDefaults standardUserDefaults] dataForKey:project];
84 if (!saved)
85 return NO;
86 BOOL stale = NO;
87 NSURL *url = [NSURL
88 URLByResolvingBookmarkData:saved
89 options:NSURLBookmarkResolutionWithSecurityScope |
90 NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutMounting
91 relativeToURL:nil
92 bookmarkDataIsStale:&stale
93 error:nil];
94 if (![url.path isEqual:project] || ![url startAccessingSecurityScopedResource])
95 return NO;
96 _scopes[project] = url;
97 if (stale)
98 [self remember:url];
99 return YES;
100}
101- (void)remember:(NSURL *)url {
102 NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
103 includingResourceValuesForKeys:nil
104 relativeToURL:nil
105 error:nil];
106 if (bookmark)
107 [[NSUserDefaults standardUserDefaults] setObject:bookmark forKey:url.path];
108}
109- (void)request:(NSString *)project {
110 if (_requesting || (_declined[project] && [_declined[project] timeIntervalSinceNow] > 0))
111 return;
112 _requesting = project;
113 NSOpenPanel *panel = [NSOpenPanel openPanel];
114 panel.delegate = self;
115 panel.canChooseDirectories = YES;
116 panel.canChooseFiles = NO;
117 panel.allowsMultipleSelection = NO;
118 panel.directoryURL = [NSURL fileURLWithPath:project isDirectory:YES];
119 panel.message = @"Allow Cage to open this mounted project in the guest terminal and editor.";
120 panel.prompt = @"Use Project";
121 _nonce = NSUUID.UUID.UUIDString;
122 _panel = panel;
123 __block NSTimer *timer;
124 [NSApp activateIgnoringOtherApps:YES];
125 [panel beginWithCompletionHandler:^(NSModalResponse response) {
126 [timer invalidate];
127 self->_panel = nil;
128 self->_nonce = nil;
129 NSURL *url = panel.URL;
130 if (response == NSModalResponseOK && [url.path isEqual:project] && mountID(project) &&
131 [url startAccessingSecurityScopedResource]) {
132 self->_scopes[project] = url;
133 [self remember:url];
134 } else {
135 self->_declined[project] = [NSDate dateWithTimeIntervalSinceNow:30];
136 }
137 self->_requesting = nil;
138 }];
139 // The request must disappear if the mount is revoked while the panel is open.
140 timer =
141 [NSTimer scheduledTimerWithTimeInterval:.25
142 repeats:YES
143 block:^(NSTimer *t) {
144 if (!mountID(project) || ![self->_requesting isEqual:project]) {
145 [panel cancel:nil];
146 return;
147 }
148 }];
149}
150- (NSString *)probe:(NSDictionary *)req {
151 NSString *project = req[@"path"], *file = req[@"file"], *expected = req[@"expected"],
152 *identity = mountID(project);
153 if (!identity || ![file isKindOfClass:NSString.class] || ![file hasPrefix:@".cage-mount-probe-"] ||
154 ![file.lastPathComponent isEqual:file] || ![expected isKindOfClass:NSString.class] ||
155 expected.length < 1 || expected.length > 256)
156 return @"ERR";
157 if (_ready[project] && ![_ready[project] isEqual:identity]) {
158 [_ready removeObjectForKey:project];
159 [_scopes[project] stopAccessingSecurityScopedResource];
160 [_scopes removeObjectForKey:project];
161 }
162 if (![self restore:project]) {
163 [self request:project];
164 return @"PENDING";
165 }
166 NSString *filePath = [project stringByAppendingPathComponent:file];
167 // Bounded read of the host challenge. A link cannot be used for the proof.
168 char b[1024];
169 int fd = open(filePath.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
170 if (fd < 0) {
171 if (errno == EPERM || errno == EACCES) {
172 [_ready removeObjectForKey:project];
173 [_scopes[project] stopAccessingSecurityScopedResource];
174 [_scopes removeObjectForKey:project];
175 [self request:project];
176 return @"PENDING";
177 }
178 return @"ERR";
179 }
180 struct stat st;
181 ssize_t n =
182 !fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_size < sizeof(b) ? read(fd, b, sizeof(b)) : -1;
183 close(fd);
184 NSData *answer = [expected dataUsingEncoding:NSUTF8StringEncoding];
185 if (n < 0 || n != (ssize_t)answer.length || memcmp(b, answer.bytes, n) ||
186 ![identity isEqual:mountID(project)])
187 return @"ERR";
188 _ready[project] = identity;
189 return @"OK";
190}
191- (void)serve {
192 struct sockaddr_un address;
193 if (!addressForSocket(&address))
194 return;
195 NSString *dir = socketPath().stringByDeletingLastPathComponent;
196 NSFileManager *fm = [NSFileManager defaultManager];
197 if (![fm createDirectoryAtPath:dir
198 withIntermediateDirectories:YES
199 attributes:@{NSFilePosixPermissions : @0700}
200 error:nil])
201 return;
202 struct stat st;
203 if (lstat(dir.fileSystemRepresentation, &st) || !S_ISDIR(st.st_mode) || st.st_uid != getuid() ||
204 (st.st_mode & 0077))
205 return;
206 // The advisory lock distinguishes a dead listener from another running copy.
207 NSString *l = [dir stringByAppendingPathComponent:@"project-terminal.lock"];
208 int lock = open(l.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600);
209 if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB)) {
210 if (lock >= 0)
211 close(lock);
212 return;
213 }
214 if (!lstat(address.sun_path, &st) && !(S_ISSOCK(st.st_mode) && st.st_uid == getuid())) {
215 close(lock);
216 return;
217 }
218 unlink(address.sun_path);
219 int listener = socket(AF_UNIX, SOCK_STREAM, 0);
220 if (listener < 0 || bind(listener, (struct sockaddr *)&address, sizeof(address)) ||
221 chmod(address.sun_path, 0600) || listen(listener, 12)) {
222 if (listener >= 0)
223 close(listener);
224 close(lock);
225 return;
226 }
227 fcntl(listener, F_SETFD, FD_CLOEXEC);
228 for (;;) {
229 int fd = accept(listener, NULL, NULL);
230 if (fd < 0) {
231 if (errno == EINTR)
232 continue;
233 break;
234 }
235 fcntl(fd, F_SETFD, FD_CLOEXEC);
236 dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
237 @autoreleasepool {
238 [self handle:fd];
239 close(fd);
240 }
241 });
242 }
243 close(listener);
244 unlink(address.sun_path);
245 close(lock);
246}
247- (void)handle:(int)fd {
248 uid_t uid;
249 gid_t gid;
250 if (getpeereid(fd, &uid, &gid) || uid != getuid())
251 return;
252 struct timeval timeout = {4, 0};
253 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
254 char bytes[8192], ancillary[CMSG_SPACE(8 * sizeof(int))];
255 int tty = -1;
256 size_t len = 0;
257 BOOL extra = NO;
258 struct iovec iov = {bytes, sizeof(bytes)};
259 struct msghdr msg = {0};
260 msg.msg_iov = &iov;
261 msg.msg_iovlen = 1;
262 msg.msg_control = ancillary;
263 msg.msg_controllen = sizeof(ancillary);
264 ssize_t n = recvmsg(fd, &msg, 0);
265 if (n <= 0)
266 return;
267 for (struct cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) {
268 if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS)
269 continue;
270 size_t count = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int);
271 int *fds = (int *)CMSG_DATA(c);
272 for (size_t i = 0; i < count; i++) {
273 if (tty < 0) {
274 tty = fds[i];
275 fcntl(tty, F_SETFD, FD_CLOEXEC);
276 } else {
277 close(fds[i]);
278 extra = YES;
279 }
280 }
281 }
282 @try {
283 if (extra || (msg.msg_flags & MSG_CTRUNC))
284 return;
285 len = (size_t)n;
286 while (!memchr(bytes, '\n', len) && len < sizeof(bytes)) {
287 n = read(fd, bytes + len, sizeof(bytes) - len);
288 if (n <= 0)
289 return;
290 len += n;
291 }
292 if (bytes[len - 1] != '\n')
293 return;
294 NSDictionary *req = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:bytes length:len]
295 options:0
296 error:nil];
297 if (![req isKindOfClass:NSDictionary.class])
298 return;
299 NSString *project = req[@"path"], *action = req[@"action"];
300 if (!mountID(project)) {
301 reply(fd, "ERR\n");
302 return;
303 }
304 // The authenticated window forwarder obtains the live NSWindow from the
305 // process that opened the panel. Closing it invalidates the nonce.
306 if ([action isEqual:@"panel"] && tty < 0) {
307 __block NSDictionary *state;
308 dispatch_sync(dispatch_get_main_queue(), ^{
309 if ([self->_requesting isEqual:project] && self->_nonce && self->_panel.visible &&
310 self->_panel.windowNumber > 0 &&
311 [self->_panel.directoryURL.URLByStandardizingPath.path isEqual:project])
312 state = @{
313 @"path" : project,
314 @"nonce" : self->_nonce,
315 @"pid" : @(getpid()),
316 @"windowNumber" : @(self->_panel.windowNumber)
317 };
318 });
319 if (!state) {
320 reply(fd, "ERR\n");
321 return;
322 }
323 NSData *json = [NSJSONSerialization dataWithJSONObject:state options:0 error:nil];
324 writeAll(fd, json.bytes, json.length);
325 reply(fd, "\n");
326 return;
327 }
328 if ([action isEqual:@"probe"] && tty < 0) {
329 __block NSString *status;
330 dispatch_sync(dispatch_get_main_queue(), ^{
331 status = [self probe:req];
332 });
333 reply(fd, [status stringByAppendingString:@"\n"].UTF8String);
334 return;
335 }
336 BOOL claude = [action isEqual:@"claude"];
337 NSString *launch = req[@"launch"];
338 if (tty < 0 || !([action isEqual:@"terminal"] || [action isEqual:@"editor"] || claude) ||
339 (claude && (![launch isKindOfClass:NSString.class] || !launch.length ||
340 [launch lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 4096))) {
341 reply(fd, "ERR\n");
342 return;
343 }
344 struct stat st;
345 char name[PATH_MAX];
346 if (fstat(tty, &st) || !S_ISCHR(st.st_mode) || st.st_uid != uid ||
347 ttyname_r(tty, name, sizeof(name)) || strncmp(name, "/dev/ttys", 9) || !isatty(tty)) {
348 reply(fd, "ERR\n");
349 return;
350 }
351 __block NSString *identity;
352 dispatch_sync(dispatch_get_main_queue(), ^{
353 identity = self->_ready[project];
354 });
355 if (!identity || ![identity isEqual:mountID(project)]) {
356 reply(fd, "ERR\n");
357 return;
358 }
359 NSString *exe = NSBundle.mainBundle.executableURL.path;
360 char *argv[] = {(char *)exe.fileSystemRepresentation, "--child",
361 (char *)project.fileSystemRepresentation, (char *)action.UTF8String,
362 claude ? (char *)launch.UTF8String : NULL, NULL};
363 posix_spawn_file_actions_t files;
364 posix_spawn_file_actions_init(&files);
365 posix_spawn_file_actions_adddup2(&files, tty, 3);
366 posix_spawnattr_t attr;
367 posix_spawnattr_init(&attr);
368 posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT);
369 pid_t pid;
370 int err = posix_spawn(&pid, argv[0], &files, &attr, argv, environ);
371 posix_spawnattr_destroy(&attr);
372 posix_spawn_file_actions_destroy(&files);
373 if (err) {
374 reply(fd, "ERR\n");
375 return;
376 }
377 reply(fd, "OK\n");
378 for (;;) {
379 int childStatus;
380 pid_t done = waitpid(pid, &childStatus, WNOHANG);
381 if (done == pid || (done < 0 && errno != EINTR))
382 break;
383 struct pollfd pollfd = {fd, POLLIN, 0};
384 if (poll(&pollfd, 1, 500) > 0 || ![identity isEqual:mountID(project)]) {
385 kill(pid, SIGHUP);
386 kill(-pid, SIGHUP);
387 for (int i = 0; i < 15; i++) {
388 if (waitpid(pid, &childStatus, WNOHANG) == pid)
389 return;
390 usleep(20000);
391 }
392 kill(pid, SIGKILL);
393 kill(-pid, SIGKILL);
394 waitpid(pid, &childStatus, 0);
395 break;
396 }
397 }
398 } @finally {
399 if (tty >= 0)
400 close(tty);
401 }
402}
403- (void)panel:(id)sender didChangeToDirectoryURL:(NSURL *)url {
404 // The host offered exactly one mounted project, and must never preview
405 // guest directories reached through the dialog's sidebar.
406 if (sender == _panel && _requesting && url && ![url.URLByStandardizingPath.path isEqual:_requesting])
407 [_panel cancel:nil];
408}
409@end
410
411static int probeCLI(int argc, char **argv) {
412 if (argc != 5)
413 return 2;
414 struct sockaddr_un address;
415 if (!addressForSocket(&address))
416 return 1;
417 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
418 if (fd < 0)
419 return 1;
420 struct timeval wait = {4, 0};
421 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait));
422 if (connect(fd, (struct sockaddr *)&address, sizeof(address))) {
423 close(fd);
424 return 1;
425 }
426 uid_t peer;
427 gid_t group;
428 if (getpeereid(fd, &peer, &group) || peer != getuid()) {
429 close(fd);
430 return 1;
431 }
432 NSData *j = [NSJSONSerialization dataWithJSONObject:@{
433 @"action" : @"probe",
434 @"path" : @(argv[2]),
435 @"file" : @(argv[3]),
436 @"expected" : @(argv[4])
437 }
438 options:0
439 error:nil];
440 BOOL ok = writeAll(fd, j.bytes, j.length) && writeAll(fd, "\n", 1);
441 FILE *f = fdopen(fd, "r");
442 if (!f) {
443 close(fd);
444 return 1;
445 }
446 char line[32] = {0};
447 if (!ok || !fgets(line, sizeof(line), f)) {
448 fclose(f);
449 return 1;
450 }
451 fclose(f);
452 if (!strcmp(line, "OK\n")) {
453 puts("OK");
454 return 0;
455 }
456 if (!strcmp(line, "PENDING\n")) {
457 puts("PENDING");
458 return 75;
459 }
460 return 1;
461}
462
463int main(int argc, char **argv) {
464 @autoreleasepool {
465 if (argc > 1 && !strcmp(argv[1], "probe"))
466 return probeCLI(argc, argv);
467 if ((argc == 4 || (argc == 5 && !strcmp(argv[3], "claude"))) && !strcmp(argv[1], "--child")) {
468 if (!mountID(@(argv[2])) || setsid() < 0 || ioctl(3, TIOCSCTTY, 0) < 0)
469 return 1;
470 for (int i = 0; i < 3; i++)
471 if (dup2(3, i) < 0)
472 return 1;
473 close(3);
474 signal(SIGPIPE, SIG_DFL);
475 if (chdir(argv[2]))
476 return 1;
477 setenv("TERM", "xterm-256color", 1);
478 setenv("PWD", argv[2], 1);
479 setenv("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", 1);
480 if (argc == 5) {
481 execl("/usr/local/libexec/cage-cli/bin/python3", "python3", "-I",
482 "/usr/local/libexec/cage-cli/macos-cli.py", "macos-launch", argv[4], (char *)NULL);
483 return 1;
484 }
485 if (!strcmp(argv[3], "terminal"))
486 execl("/bin/zsh", "-zsh", (char *)NULL);
487 if (!strcmp(argv[3], "editor"))
488 execl("/usr/local/libexec/cage-macos-editor", "cage-macos-editor", (char *)NULL);
489 return 1;
490 }
491 if (argc != 1)
492 return 2;
493 signal(SIGPIPE, SIG_IGN);
494 umask(0077);
495 NSApplication *app = NSApplication.sharedApplication;
496 ProjectAccess *delegate = [[ProjectAccess alloc] init];
497 app.delegate = delegate;
498 [app setActivationPolicy:NSApplicationActivationPolicyAccessory];
499 [app run];
500 return 0;
501 }
502}