@capybara-hq/plugin-sdk 0.1.0-rc.38 → 0.1.0-rc.39

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.
@@ -8,12 +8,15 @@ import { SANDBOX_WRITE_POLICY_PYTHON } from "./sandbox-write-denies.js";
8
8
  * Descriptor-relative native access alone does not establish an OS execution boundary.
9
9
  */
10
10
  export const NATIVE_FILES_SOURCE = String.raw `import base64
11
+ import contextlib
11
12
  import errno
13
+ import fcntl
12
14
  import json
13
15
  import os
14
16
  import re
15
17
  import stat
16
18
  import sys
19
+ import time
17
20
  import urllib.parse
18
21
 
19
22
  MAX_DEPTH = ${MAX_DEVICE_SCAN_DEPTH}
@@ -22,6 +25,14 @@ MAX_RESULTS = ${MAX_DEVICE_SCAN_RESULTS}
22
25
  MAX_NAME = ${MAX_DEVICE_PROJECT_NAME_LENGTH}
23
26
  SKIP_ANY = ${JSON.stringify(DEVICE_SCAN_SKIPPED_DIRS)}
24
27
  SKIP_BASE = ${JSON.stringify(DEVICE_SCAN_SKIPPED_BASE_DIRS)}
28
+ # How long a write waits for a guarded move of the device (which holds the device's files lock
29
+ # exclusively for a few renames) before it fails with EBUSY: only a lock held from outside every
30
+ # sandbox (Full work of the owner) can take that long.
31
+ SHARED_WAIT_S = 30
32
+ # A test seam (pause_mkdir): a write creating that directory pauses PAUSE_S between its check and
33
+ # its mkdir, announced by PAUSE_MARKER in the parent. Never set in production.
34
+ PAUSE_S = 2
35
+ PAUSE_MARKER = ".capybara-test-paused"
25
36
  # ECMAScript whitespace (Python's str.strip also removes several extra control characters).
26
37
  SPACE = "\u0009\u000a\u000b\u000c\u000d\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
27
38
 
@@ -59,10 +70,61 @@ def valid_name(name):
59
70
  and not re.search(r"[\x00-\x1f\x7f/]", name)
60
71
  and name[0] not in SPACE and name[-1] not in SPACE)
61
72
 
73
+ class DeviceFilesLock:
74
+ """The device's files lock, shared by every operation of the device: an flock on a file outside
75
+ every sandbox, inherited as a descriptor ("filesLockFd") that the restricted command never
76
+ holds. Every acquisition reopens it through /proc/self/fd (this process is non-dumpable, so no
77
+ other process can), because flock belongs to an open file description: each holder needs its
78
+ own. The launcher's broker and the device agent's native writes take it. Shared and exclusive acquisitions both poll without blocking up to their bound, so a
79
+ waiting exclusive holder never holds back new shared ones (as in the launcher's in-process SharedLock)."""
80
+
81
+ def __init__(self, fd):
82
+ self.fd = fd
83
+
84
+ def acquire(self, mode, timeout, message):
85
+ fd = os.open("/proc/self/fd/%d" % self.fd, os.O_RDONLY | os.O_CLOEXEC)
86
+ deadline = time.monotonic() + timeout
87
+ delay = 0.0005
88
+ while True:
89
+ try:
90
+ fcntl.flock(fd, mode | fcntl.LOCK_NB)
91
+ return fd
92
+ except OSError as error:
93
+ if error.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EINTR):
94
+ os.close(fd)
95
+ raise
96
+ if time.monotonic() >= deadline:
97
+ os.close(fd)
98
+ raise OSError(errno.EBUSY, message)
99
+ time.sleep(delay)
100
+ delay = min(delay * 2, 0.005)
101
+
102
+ @contextlib.contextmanager
103
+ def shared(self):
104
+ fd = self.acquire(fcntl.LOCK_SH, SHARED_WAIT_S, "A guarded move of the device did not end")
105
+ try:
106
+ yield
107
+ finally:
108
+ os.close(fd) # closing the last descriptor of the description releases the lock
109
+
110
+ @contextlib.contextmanager
111
+ def exclusive(self, timeout):
112
+ """Raises EBUSY when the shared holders do not leave within timeout seconds."""
113
+ fd = self.acquire(fcntl.LOCK_EX, timeout, "The device's other writes did not finish")
114
+ try:
115
+ yield
116
+ finally:
117
+ os.close(fd)
118
+
119
+
62
120
  class NativeFiles:
63
121
  def __init__(self, roots):
64
122
  self.roots = roots
65
123
  self.deny_writes = roots.get("denyWrites") is True
124
+ self.pause_mkdir = None
125
+ # The device's files lock (DeviceFilesLock), held shared by a write from its check to its
126
+ # effect; set by a consumer serving one device's operations, never by the transport.
127
+ self.files_lock = None
66
128
  # Descriptors are supplied by the trusted consumer, never reopened by root pathname.
67
129
  for root in roots["read"] + roots["write"]:
68
130
  if not valid_path(root["path"]) or os.path.normpath(root["path"]) != root["path"]:
@@ -104,11 +166,18 @@ class NativeFiles:
104
166
  if not final and create:
105
167
  if self.deny_writes and write_denied(os.path.join(current, name)):
106
168
  raise ScopeDenied("Native path is a protected write target")
169
+ if self.pause_mkdir is not None and name == self.pause_mkdir:
170
+ os.close(os.open(PAUSE_MARKER, os.O_WRONLY | os.O_CREAT | os.O_EXCL,
171
+ 0o644, dir_fd=fd))
172
+ time.sleep(PAUSE_S)
107
173
  try:
108
174
  os.mkdir(name, 0o755, dir_fd=fd)
175
+ made = True
109
176
  except FileExistsError:
110
- pass
177
+ made = False
111
178
  info = os.stat(name, dir_fd=fd, follow_symlinks=False)
179
+ if made:
180
+ self.settle(fd, name, (info.st_dev, info.st_ino), True)
112
181
  elif final and not must_exist:
113
182
  return fd, name, os.path.normpath(os.path.join(current, name)), links
114
183
  else:
@@ -154,6 +223,56 @@ class NativeFiles:
154
223
  os.close(fd)
155
224
  raise
156
225
 
226
+ # ---- post-effect verification (restricted roots) -----------------------------------------
227
+ # A write is checked on the path its parent had, then applied through the parent descriptor.
228
+ # The device's files lock keeps sandboxed guarded moves out of that window; a process outside
229
+ # the sandbox can still move the parent meanwhile. So each entry this helper creates is checked
230
+ # again at its parent's current place (Linux /proc; elsewhere there is no such check) and
231
+ # undone when it landed at a protected path.
232
+
233
+ def placed(self, fd, name):
234
+ """name below fd at fd's current path, mapped onto the roots' recorded paths; None where
235
+ that cannot be told (no /proc) or the directory is gone."""
236
+ try:
237
+ where = os.readlink("/proc/self/fd/%d" % fd)
238
+ except OSError:
239
+ return None
240
+ if not where.startswith("/") or where.endswith(" (deleted)"):
241
+ return None
242
+ best = None
243
+ for root in self.roots["read"] + self.roots["write"]:
244
+ try:
245
+ now = os.readlink("/proc/self/fd/%d" % root["fd"]).rstrip("/")
246
+ except OSError:
247
+ continue
248
+ if where == now or where.startswith(now + "/"):
249
+ if best is None or len(now) > best[0]:
250
+ best = (len(now), root["path"].rstrip("/") + where[len(now):])
251
+ where = best[1] if best else where
252
+ return where.rstrip("/") + "/" + name
253
+
254
+ def landed_denied(self, fd, name, is_dir):
255
+ now = self.placed(fd, name) if self.deny_writes else None
256
+ return now is not None and (write_denied(now) or (
257
+ not is_dir and _fold_parts(name) == [".git"]))
258
+
259
+ def settle(self, fd, name, made, is_dir):
260
+ """Undoes the entry this helper made below fd (made: its (st_dev, st_ino)) when it now
261
+ sits at a protected path, and refuses."""
262
+ if not self.landed_denied(fd, name, is_dir):
263
+ return
264
+ try:
265
+ info = os.stat(name, dir_fd=fd, follow_symlinks=False)
266
+ if (info.st_dev, info.st_ino) != made:
267
+ raise OSError(errno.ESTALE, "The created entry was replaced")
268
+ if is_dir:
269
+ os.rmdir(name, dir_fd=fd)
270
+ else:
271
+ os.unlink(name, dir_fd=fd)
272
+ except OSError:
273
+ raise ScopeDenied("A native write landed at a protected path and could not be undone")
274
+ raise ScopeDenied("Native path became a protected write target")
275
+
157
276
  def open(self, path, write=False, directory=False):
158
277
  parent, name = self.parent(path, write, write)
159
278
  try:
@@ -165,7 +284,26 @@ class NativeFiles:
165
284
  flags |= os.O_WRONLY | os.O_CREAT if write else os.O_RDONLY
166
285
  if directory:
167
286
  flags |= os.O_DIRECTORY
168
- return os.open(name, flags, 0o600, dir_fd=parent)
287
+ if not write:
288
+ return os.open(name, flags, 0o600, dir_fd=parent)
289
+ try:
290
+ os.stat(name, dir_fd=parent, follow_symlinks=False)
291
+ existed = True
292
+ except FileNotFoundError:
293
+ existed = False
294
+ fd = os.open(name, flags, 0o600, dir_fd=parent)
295
+ try:
296
+ if existed:
297
+ # nothing was made: refused before any byte changes (the caller truncates)
298
+ if self.landed_denied(parent, name, False):
299
+ raise ScopeDenied("Native path became a protected write target")
300
+ else:
301
+ info = os.fstat(fd)
302
+ self.settle(parent, name, (info.st_dev, info.st_ino), False)
303
+ except BaseException:
304
+ os.close(fd)
305
+ raise
306
+ return fd
169
307
  finally:
170
308
  if parent is not None:
171
309
  os.close(parent)
@@ -284,7 +422,9 @@ class NativeFiles:
284
422
  "truncated": info.st_size > bound}
285
423
  if method == "writeFile":
286
424
  data = base64.b64decode(request["dataB64"], validate=True)
287
- fd = self.open(path, write=True)
425
+ with (self.files_lock.shared() if self.files_lock is not None
426
+ else contextlib.nullcontext()):
427
+ fd = self.open(path, write=True)
288
428
  try:
289
429
  if not stat.S_ISREG(os.fstat(fd).st_mode):
290
430
  raise ValueError("Native writes require a regular file")
@@ -45,7 +45,16 @@ export type SandboxNetworkScope = {
45
45
  } | {
46
46
  readonly kind: "allowlist";
47
47
  readonly hosts: readonly string[];
48
- } | {
48
+ }
49
+ /**
50
+ * The public internet, decided on the resolved address against `AddressClass`
51
+ * (`network-classes.ts`): every class in `OPEN_PUBLIC_DENIED_CLASSES` stays closed.
52
+ */
53
+ | {
54
+ readonly kind: "open-public";
55
+ }
56
+ /** Only with `filesystem: { kind: "device" }` (and the reverse): the escalated (outside) call. */
57
+ | {
49
58
  readonly kind: "environment";
50
59
  };
51
60
  /** An operation locator for idempotent admission and revocation, never a credential. */
@@ -70,19 +79,41 @@ export interface SandboxOperationScope extends SandboxOperationRef {
70
79
  readonly filesystem: SandboxFileScope;
71
80
  readonly network: SandboxNetworkScope;
72
81
  }
73
- /** Runtime support, not consent. Restricted support requires all four claims together. */
82
+ /**
83
+ * Where a provider's sandbox boundary lies: around each operation (the OS sandbox of a local device,
84
+ * the Linux per-operation runtime) or around the whole instance (a cloud container or microVM).
85
+ */
86
+ export type SandboxBoundary = "operation" | "instance";
87
+ /**
88
+ * Runtime support, version 2 (approval-only profiles design, "SDK and protocol"). `boundary:
89
+ * "instance"` with `restricted: null` is a supported device whose scope is the whole instance.
90
+ * `outsideSandbox` says whether a call can run outside the sandbox (an escalated call). Runtime
91
+ * support, not consent.
92
+ */
74
93
  export interface SandboxPermissionSupport {
75
- readonly version: 1;
94
+ readonly version: 2;
95
+ readonly boundary: SandboxBoundary;
76
96
  readonly restricted: {
77
97
  readonly filesystem: true;
78
98
  readonly network: true;
79
99
  readonly native: true;
80
100
  readonly concurrentScopes: true;
81
101
  } | null;
82
- readonly fullAccess: boolean;
102
+ readonly network: {
103
+ readonly openPublic: boolean;
104
+ readonly allowlist: boolean;
105
+ readonly perOperationHosts: boolean;
106
+ };
107
+ readonly outsideSandbox: boolean;
83
108
  readonly background: boolean;
84
109
  readonly unavailableReason?: string;
85
110
  }
111
+ /**
112
+ * Whether a report is a supported instance boundary: `boundary: "instance"` with no
113
+ * `unavailableReason`. An instance report naming a reason (a stale image, a digest mismatch)
114
+ * claims nothing, so a device reporting it is unsupported, never the whole-instance sandbox.
115
+ */
116
+ export declare function instanceSupported(report: SandboxPermissionSupport): boolean;
86
117
  /** Actor and tag come only from the immutable operation scope. */
87
118
  export type SandboxExecOptions = Omit<Parameters<SandboxProvider["exec"]>[1], "tag" | "actor">;
88
119
  /**
@@ -242,6 +273,7 @@ export declare function parseSandboxOperationRef(value: unknown): SandboxOperati
242
273
  * IDs and ceiling revisions are bounded to 128 characters; roots to 64 paths of at most 4096 characters;
243
274
  * hosts to 100 entries passing validateAllowHost. Empty grants stay empty, including deny-all.
244
275
  * Performs no I/O, authority lookup or deadline refresh. Unknown fields are rejected at every level.
276
+ * The `environment` network and the `device` filesystem are accepted only together.
245
277
  */
246
278
  export declare function parseSandboxOperationScope(value: unknown): SandboxOperationScope;
247
279
  /** Validates an owner browsing grant and returns a deeply frozen copy; no conversation is required. */
@@ -59,6 +59,14 @@ export function isSandboxOperationOutcomeUnknownError(e) {
59
59
  e.name === "SandboxOperationOutcomeUnknownError" &&
60
60
  e.sandboxOperationOutcomeUnknown === true);
61
61
  }
62
+ /**
63
+ * Whether a report is a supported instance boundary: `boundary: "instance"` with no
64
+ * `unavailableReason`. An instance report naming a reason (a stale image, a digest mismatch)
65
+ * claims nothing, so a device reporting it is unsupported, never the whole-instance sandbox.
66
+ */
67
+ export function instanceSupported(report) {
68
+ return report.boundary === "instance" && report.unavailableReason === undefined;
69
+ }
62
70
  function invalid(field, requirement) {
63
71
  throw new SandboxScopeValidationError(`Invalid ${field}: ${requirement}. Supply a valid scope or reference before retrying.`);
64
72
  }
@@ -136,12 +144,12 @@ function fileScope(value) {
136
144
  }
137
145
  function networkScope(value) {
138
146
  const v = record(value, ["kind", "hosts"], "network");
139
- if (v.kind === "none" || v.kind === "environment") {
147
+ if (v.kind === "none" || v.kind === "open-public" || v.kind === "environment") {
140
148
  record(value, ["kind"], "network");
141
149
  return Object.freeze({ kind: v.kind });
142
150
  }
143
151
  if (v.kind !== "allowlist")
144
- return invalid("network.kind", "expected none, allowlist or environment");
152
+ return invalid("network.kind", "expected none, allowlist, open-public or environment");
145
153
  return Object.freeze({
146
154
  kind: "allowlist",
147
155
  hosts: strings(v.hosts, 100, validateAllowHost, "network.hosts"),
@@ -170,6 +178,7 @@ export function parseSandboxOperationRef(value) {
170
178
  * IDs and ceiling revisions are bounded to 128 characters; roots to 64 paths of at most 4096 characters;
171
179
  * hosts to 100 entries passing validateAllowHost. Empty grants stay empty, including deny-all.
172
180
  * Performs no I/O, authority lookup or deadline refresh. Unknown fields are rejected at every level.
181
+ * The `environment` network and the `device` filesystem are accepted only together.
173
182
  */
174
183
  export function parseSandboxOperationScope(value) {
175
184
  const v = record(value, [
@@ -187,6 +196,14 @@ export function parseSandboxOperationScope(value) {
187
196
  ], "operation scope");
188
197
  if (!isPermissionProfile(v.profile))
189
198
  return invalid("profile", "expected request-approval, approve-for-me or full-access");
199
+ const filesystem = fileScope(v.filesystem);
200
+ const network = networkScope(v.network);
201
+ // The device filesystem and the environment network are the two halves of the escalated call:
202
+ // neither ever pairs with a sandboxed counterpart.
203
+ if (network.kind === "environment" && filesystem.kind !== "device")
204
+ return invalid("network.kind: environment requires the device filesystem", "a scoped filesystem takes none, allowlist or open-public");
205
+ if (filesystem.kind === "device" && network.kind !== "environment")
206
+ return invalid("filesystem.kind: device requires the environment network", "the device filesystem is only the escalated call's");
190
207
  return Object.freeze({
191
208
  ...operationRef(v),
192
209
  deviceId: id(v.deviceId, "deviceId"),
@@ -196,8 +213,8 @@ export function parseSandboxOperationScope(value) {
196
213
  profile: v.profile,
197
214
  actor: actor(v.actor),
198
215
  tag: tag(v.tag),
199
- filesystem: fileScope(v.filesystem),
200
- network: networkScope(v.network),
216
+ filesystem,
217
+ network,
201
218
  });
202
219
  }
203
220
  /** Validates an owner browsing grant and returns a deeply frozen copy; no conversation is required. */
@@ -17,12 +17,12 @@ export const SANDBOX_RUNTIME_SOURCE = Object.freeze({
17
17
  Object.freeze({
18
18
  name: "native-files.py",
19
19
  source: NATIVE_FILES_SOURCE,
20
- sha256: "09a78c9bb7264ad6a1fe3b1aadd4c0f489192dc47c903c7fcc42fdf405590b42",
20
+ sha256: "9bde40a697fd60f2c9073b7fc35e84b4cffd045463e3ab5116a2c3435fd55df0",
21
21
  }),
22
22
  Object.freeze({
23
23
  name: "linux-sandbox.py",
24
24
  source: LINUX_SANDBOX_SOURCE,
25
- sha256: "b17b714a445912508d5082598af42960df550387c4a73b379561af19b0b45c87",
25
+ sha256: "4e046df902dc644532ada9f2a3bef30a983daf7d1f238bd46dcd16524d96c66c",
26
26
  }),
27
27
  ]),
28
28
  });
@@ -5,8 +5,11 @@
5
5
  * from executing what a restricted command left behind.
6
6
  *
7
7
  * 1. {@link SANDBOX_MANDATORY_WRITE_DENIES}: component sequences denied wherever they appear (the
8
- * entry and everything beneath it): shell startup files, git's global files, direnv and npm
9
- * configuration, editor and agent configuration.
8
+ * entry and everything beneath it): shell startup and logout files, git's global files, direnv
9
+ * and npm configuration, editor and agent configuration, and the OS persistence locations
10
+ * (launchd, systemd, environment.d, XDG and KDE autostart, X session files, fish). Entries are
11
+ * written already folded. {@link SANDBOX_SYSTEM_WRITE_DENIES}: absolute system paths denied
12
+ * with everything beneath them (the crontab and at spools), anchored at `/`.
10
13
  * 2. Inside a `.git` directory (the first `.git` component of a path) only git's ordinary
11
14
  * internals are writable, an allowlist ({@link SANDBOX_GIT_ALLOWED_DIRECTORIES},
12
15
  * {@link SANDBOX_GIT_ALLOWED_FILES}, `info/exclude`). Everything else there is denied:
@@ -16,14 +19,23 @@
16
19
  * any reading of its name would make it a denied internal.
17
20
  * 3. Outside `.git`, a file named `HEAD` is denied: with `objects/` and `refs/` it would make a
18
21
  * bare-repository lookalike whose configuration git honours.
19
- * 4. Moves ({@link isSandboxMoveDenied}): nothing leaves a protected name (`.git`, `.claude`, …)
20
- * except within the same protected directory; a directory is not moved under a protected name
21
- * from outside it; no non-directory becomes `.git` (a `gitdir:` pointer).
22
+ * 4. Moves ({@link isSandboxMoveDenied}): neither end may be a denied write; nothing leaves a
23
+ * protected name ({@link SANDBOX_PROTECTED_PATH_NAMES}: `.git` and the single-component
24
+ * entries) except within the same protected directory; a directory is not moved under a
25
+ * protected name from outside it; no non-directory becomes `.git` (a `gitdir:` pointer). For a
26
+ * multi-component entry `[a, b, …]` (or an absolute system path) a destination ending in a
27
+ * proper prefix of it (`…/a`) takes no non-directory (a link there would redirect the entry)
28
+ * and no directory holding the entry's next component (`b`): a prepared directory never moves
29
+ * into place, while ordinary names (`library`, `.config`) stay movable. An ancestor of an
30
+ * anchored path (a system path, or a consumer's resolved target) never moves away.
22
31
  *
23
32
  * 5. Inside an allowlisted subtree nothing can make a repository: no `.git`, no `HEAD` except
24
33
  * where git keeps one (`logs/HEAD`, `refs/remotes/<r>/HEAD`, …), and no `objects`, `commondir`
25
34
  * or `gitdir` beside such a `HEAD`.
26
35
  *
36
+ * 6. A component starting with {@link SANDBOX_RESERVED_NAME_PREFIX} (the broker's staging and
37
+ * quarantine names) is denied with everything beneath it.
38
+ *
27
39
  * Names are compared after Unicode NFKC normalization and full case folding
28
40
  * ({@link sandboxFoldName}, identical to Python's `casefold`). Known limitations: a
29
41
  * restricted command cannot `git init`, add a submodule or worktree, or create a bare repository;
@@ -33,8 +45,51 @@
33
45
  * (its state directories are writable for git's own use) and continuing it runs its `exec` lines.
34
46
  * The macOS worker expresses this policy as ordered Seatbelt regex rules
35
47
  * (`packages/device/src/exec/mac-write-policy.ts`).
48
+ *
49
+ * Constraints on consumers:
50
+ *
51
+ * - The policy judges the path it is given. A protected home location reached through a symbolic
52
+ * link (`~/.config` or `~/Library` linked elsewhere, as dotfile managers do) is denied only at
53
+ * its resolved target: a device worker resolves the protected home locations at operation start
54
+ * and adds their resolved targets as absolute denies.
55
+ * - The move check needs the entries of a moved directory. A consumer passes them from the source
56
+ * descriptor; the Python `move_denied` otherwise lists the source path, refusing when it cannot.
57
+ * A listing is a snapshot: a concurrent writer could add the next component between the check
58
+ * and the rename, so a consumer that can re-checks the destination after the rename.
36
59
  */
37
60
  export declare const SANDBOX_MANDATORY_WRITE_DENIES: readonly (readonly string[])[];
61
+ /**
62
+ * Locations denied only directly under the device owner's home, with everything beneath them, never
63
+ * elsewhere: `~/bin`, a directory many shells put on `PATH`, where a planted program would shadow a
64
+ * system one in the owner's later unsandboxed shell (a project's own `bin/` stays writable).
65
+ * Consumers anchor each entry at the home they protect: the device workers add it, and the target
66
+ * of a link it is, as absolute denies; the kernel never proposes it as a write directory
67
+ * ({@link isSandboxHomeWriteDenied}). `~/.local/bin` and `~/.cargo/bin` are
68
+ * {@link SANDBOX_MANDATORY_WRITE_DENIES} entries.
69
+ */
70
+ export declare const SANDBOX_HOME_WRITE_DENIES: readonly (readonly string[])[];
71
+ /**
72
+ * System runtime and socket directories (compared folded, anchored at `/`): other programs keep
73
+ * their UNIX sockets and device nodes there (`/run/user/<uid>/bus`, `/var/run/docker.sock`,
74
+ * `/dev`, `/proc`), so a restricted write root never is one, lies inside one or contains one
75
+ * ({@link sandboxRuntimeDirectoryOf}).
76
+ */
77
+ export declare const SANDBOX_RUNTIME_DIRECTORIES: readonly string[];
78
+ /**
79
+ * Absolute system paths denied with everything beneath them, compared folded and anchored at `/`:
80
+ * the crontab and at spools of Linux (`/var/spool/cron` in its `crontabs` and `tabs` layouts,
81
+ * `/var/spool/at`) and macOS (`/private/var/at`, also spelled `/var/at`; `/usr/lib/cron/tabs` is a
82
+ * link resolving there). Never protected move names: a project's own `at/` or `spool/` stays
83
+ * ordinary.
84
+ */
85
+ export declare const SANDBOX_SYSTEM_WRITE_DENIES: readonly string[];
86
+ /**
87
+ * The name prefix the Linux broker reserves for its own staging (a directory checked before it
88
+ * moves into a guarded place) and quarantine names. Any path with a component starting with it
89
+ * (compared folded) is denied to every sandboxed write, so nothing sandboxed can create, write
90
+ * into, or move into or out of such a directory.
91
+ */
92
+ export declare const SANDBOX_RESERVED_NAME_PREFIX = ".capybara-staging-";
38
93
  /** Directories inside a gitdir whose whole subtree is writable (objects, refs, operation state). */
39
94
  export declare const SANDBOX_GIT_ALLOWED_DIRECTORIES: readonly string[];
40
95
  /** Entries directly in a gitdir that are writable, each also with a `.lock` suffix. */
@@ -45,14 +100,38 @@ export declare const SANDBOX_GIT_ALLOWED_FILES: readonly string[];
45
100
  * express the allowlist or the `HEAD` rule exactly; see the rules above.
46
101
  */
47
102
  export declare const SANDBOX_GIT_DENIED_INTERNALS: readonly string[];
48
- /** Names nothing leaves, and no directory is moved under, from outside. */
103
+ /**
104
+ * Names nothing leaves, and no directory is moved under, from outside: `.git` and the
105
+ * single-component entries. A multi-component entry is guarded by its prefix rule instead (rule 4),
106
+ * so its first component (`library`, `.config`) stays an ordinary name.
107
+ */
49
108
  export declare const SANDBOX_PROTECTED_PATH_NAMES: readonly string[];
50
109
  /** NFKC, then full case folding: the same as Python's `normalize("NFKC", s).casefold()`. */
51
110
  export declare function sandboxFoldName(name: string): string;
111
+ /**
112
+ * The system runtime or socket directory a restricted write root `root` (absolute, normalized) is,
113
+ * lies inside or contains, or null: {@link SANDBOX_RUNTIME_DIRECTORIES} with everything beneath
114
+ * them; `/tmp` and `/private/tmp` themselves (a subdirectory is fine unless it is a known socket
115
+ * directory such as `/tmp/.X11-unix`, `/tmp/tmux-<uid>` or `/tmp/ssh-*`, or lies inside one); and
116
+ * every ancestor of one (`/var`, `/private`). The kernel's candidate builder and admission and the
117
+ * device's root check refuse such a root: a socket there may belong to a process outside the
118
+ * sandbox (the Linux broker also refuses every pathname UNIX connect to a socket the operation did
119
+ * not bind itself).
120
+ */
121
+ export declare function sandboxRuntimeDirectoryOf(root: string): string | null;
122
+ /**
123
+ * Whether `path` (absolute, normalized) is a {@link SANDBOX_HOME_WRITE_DENIES} location under
124
+ * `home`, or beneath one (names compared folded).
125
+ */
126
+ export declare function isSandboxHomeWriteDenied(path: string, home: string): boolean;
52
127
  /** Whether restricted execution may never write `path` (an absolute, normalized path). */
53
128
  export declare function isSandboxWriteDenied(path: string): boolean;
54
- /** Whether a restricted rename or link of `source` to `destination` is refused (rule 4). */
55
- export declare function isSandboxMoveDenied(source: string, destination: string, sourceIsDirectory: boolean): boolean;
129
+ /**
130
+ * Whether a restricted rename or link of `source` to `destination` is refused (rule 4).
131
+ * `sourceEntries` are the names directly in a moved directory; the check needs them only when the
132
+ * destination ends in a proper prefix of a guarded entry, and without them it refuses.
133
+ */
134
+ export declare function isSandboxMoveDenied(source: string, destination: string, sourceIsDirectory: boolean, sourceEntries?: readonly string[]): boolean;
56
135
  /**
57
136
  * The same policy for the Python consumers (`linux-sandbox.py`, `native-files.py`): defines
58
137
  * `write_denied(path)` and `move_denied(source, destination, is_dir)` with identical rules.