@commonlyai/cli 0.1.383 → 0.1.385

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.383",
3
+ "version": "0.1.385",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -26,6 +26,7 @@ import { createHash } from 'crypto';
26
26
 
27
27
  import { requireSeatModel } from '../lib/adapters/seat-model.js';
28
28
  import { createClient } from '../lib/api.js';
29
+ import { connectCodeRefusalLine, redeemConnectCode, savedKeyNote } from '../lib/connect-code.js';
29
30
  import {
30
31
  buildSpawnId,
31
32
  createSpawnCredentialLease,
@@ -5873,6 +5874,8 @@ Docs:
5873
5874
  .option('--refusal-handoff <agent>', 'Agent to @mention when the model provider refuses a request\'s content; the request is acked as refused, never retried')
5874
5875
  .option('--allow <grants>', 'On first run of an agent that works in its folder, also let it edit files and run commands (write) and/or fetch web pages (web), comma-separated. Commands reach the network.')
5875
5876
  .option('--unsandboxed', 'Native Windows, or a private Codex agent on Linux: run this agent without a sandbox, with your own access to files and commands. It gets no connector grants. Codex can run commands in invite-only pods, where anyone in the pod, including people invited later, can direct it.')
5877
+ .option('--api-url <url>', 'The Commonly instance this agent joins (the Connect your own agent page fills it in; same as COMMONLY_API_URL)')
5878
+ .option('--connect <code>', "The connect code from the Connect your own agent page's line, traded once for this agent's key; it stops working once the agent has listened, or after 30 minutes")
5876
5879
  .action(async (typedName, opts) => {
5877
5880
  // F306: the seat this run is. `name` is the local key (the token file,
5878
5881
  // the log label, the daemon's plist); the server identity is the record's.
@@ -5912,6 +5915,42 @@ Docs:
5912
5915
  name = agentArg;
5913
5916
  }
5914
5917
  }
5918
+ // F525: the page's one pasted line names the instance and carries a
5919
+ // connect code, not the agent's lasting key, so the shell history it
5920
+ // lands in keeps nothing that still works once the agent has listened.
5921
+ // The key it trades for takes the env path's place from here on: the
5922
+ // first run bootstraps from it, and a saved record treats it as a
5923
+ // reissued key (adoptEnvToken).
5924
+ // A saved agent of this name on another instance would win over the
5925
+ // line's key and run as that one, leaving this one waiting. Checked for
5926
+ // --api-url, and again for the instance the code is redeemed on however
5927
+ // it was named (--api-url, COMMONLY_API_URL or the saved config).
5928
+ const savedOrigin = (() => {
5929
+ try { return record?.instanceUrl ? new URL(record.instanceUrl).origin : null; } catch { return null; }
5930
+ })();
5931
+ const refuseOtherInstance = (lineOrigin) => {
5932
+ if (!savedOrigin || !lineOrigin || savedOrigin === lineOrigin) return;
5933
+ console.error(`${stamp()} [${name}] This computer already runs an agent called ${agentArg} on ${savedOrigin}, `
5934
+ + `and this line is for ${lineOrigin}. To use this line, remove that one first: `
5935
+ + `${CLI} agent detach ${name} --force, then paste the line again.`);
5936
+ process.exit(1);
5937
+ };
5938
+ if (opts.apiUrl !== undefined) {
5939
+ let apiUrl;
5940
+ try {
5941
+ apiUrl = new URL(String(opts.apiUrl).trim());
5942
+ } catch {
5943
+ apiUrl = null;
5944
+ }
5945
+ if (!apiUrl || !['https:', 'http:'].includes(apiUrl.protocol) || apiUrl.search || apiUrl.hash) {
5946
+ console.error(`${stamp()} [${name}] --api-url needs an http(s) address, such as https://api.commonly.me.`);
5947
+ process.exit(1);
5948
+ }
5949
+ // As typed, less a trailing slash, as the env path keeps it.
5950
+ const typedUrl = String(opts.apiUrl).trim().replace(/\/+$/, '');
5951
+ refuseOtherInstance(apiUrl.origin);
5952
+ process.env.COMMONLY_API_URL = typedUrl;
5953
+ }
5915
5954
  // F515: Node first, before anything uses the token: on a Node without
5916
5955
  // fetch, the first call fails and reads as a bad token. A first run stops
5917
5956
  // here and says so, telling the instance when it can; a seat with a saved
@@ -5929,6 +5968,28 @@ Docs:
5929
5968
  }
5930
5969
  process.exit(1);
5931
5970
  }
5971
+ let connectCodeKey = false;
5972
+ if (opts.connect !== undefined) {
5973
+ const instanceUrl = (process.env.COMMONLY_API_URL || '').trim() || resolveInstanceUrl(undefined);
5974
+ refuseOtherInstance((() => {
5975
+ try { return new URL(instanceUrl).origin; } catch { return null; }
5976
+ })());
5977
+ const redeemed = await redeemConnectCode({ code: String(opts.connect).trim(), instanceUrl });
5978
+ if (redeemed.token) {
5979
+ process.env.COMMONLY_AGENT_TOKEN = redeemed.token;
5980
+ connectCodeKey = true;
5981
+ } else if (record) {
5982
+ // The line again, from shell history, on the computer this agent
5983
+ // already runs on: its code is spent or expired, or the instance
5984
+ // can't be reached just now. The saved token is what to run.
5985
+ console.log(`${stamp()} [${name}] ${savedKeyNote(redeemed.refusal)}`);
5986
+ } else {
5987
+ console.error(`${stamp()} [${name}] ${connectCodeRefusalLine(redeemed.refusal, {
5988
+ name: agentArg, runName: name, instanceUrl, detail: redeemed.detail, status: redeemed.status,
5989
+ })}`);
5990
+ process.exit(1);
5991
+ }
5992
+ }
5932
5993
  let bootstrapped = false;
5933
5994
  const saved = record;
5934
5995
  const savedRefusal = record && named ? runInstanceRefusal({ record, instanceId }) : null;
@@ -6085,7 +6146,7 @@ Docs:
6085
6146
  // belongs to another name).
6086
6147
  if (named) name = savedAs;
6087
6148
  saveAgentToken(savedAs, record);
6088
- console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(savedAs)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`);
6149
+ console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(savedAs)} from ${connectCodeKey ? 'the connect code' : 'COMMONLY_AGENT_TOKEN'} (adapter: ${record.adapter})`);
6089
6150
  } else if (savedSeatLacksDefaultSandbox(record)) {
6090
6151
  console.warn(
6091
6152
  `${stamp()} [${name}] this agent's saved settings declare no sandbox, so it runs without one. `
@@ -89,6 +89,7 @@ import {
89
89
  import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
90
90
  import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
91
91
  import { holdWorkspaceRealpath, workspacePinDir } from '../sandbox/workspace-pin.js';
92
+ import { closeHeldPaths, openHeldPath } from '../sandbox/bind-fd.js';
92
93
  import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from '../sandbox/mode.js';
93
94
  import { UNSANDBOXED_FLAG } from '../sandbox/host-check.js';
94
95
  import {
@@ -936,7 +937,7 @@ const runClaude = ({
936
937
  cmd, args, cwd, env, timeoutMs, credentials = [], spawnImpl = childSpawn, onSpawn, controls = {}, ownGroup = false,
937
938
  transcriptPath = null, firstOutputMs = firstOutputWindowMs(), lockProbe, stallKillGraceMs = STALL_KILL_GRACE_MS,
938
939
  processTable = readProcessTable, survivorIo, modelStream = true, turnReap = turnReapEnabled(),
939
- commandResolution = {}, confined = false,
940
+ commandResolution = {}, confined = false, passFds = [],
940
941
  }) => new Promise((resolve, reject) => {
941
942
  // Every process the turn starts inherits this marker however it detaches,
942
943
  // so what it leaves running is stopped once the turn has closed. A confined
@@ -945,11 +946,19 @@ const runClaude = ({
945
946
  // On Windows an npm `claude.cmd` is read, not run through cmd.exe: the
946
947
  // prompt in `args` is pod content (#2141). Off Windows this is identity.
947
948
  const launch = resolveLaunch(cmd, args, { env: turn.env, ...commandResolution });
948
- const proc = spawnInOwnGroup(spawnImpl, launch.command, launch.args, {
949
- cwd,
950
- env: turn.env,
951
- stdio: ['ignore', 'pipe', 'pipe'],
952
- }, { ownGroup });
949
+ let proc;
950
+ try {
951
+ proc = spawnInOwnGroup(spawnImpl, launch.command, launch.args, {
952
+ cwd,
953
+ env: turn.env,
954
+ // F211: bind sources bwrap mounts by descriptor arrive as fds 3 and up.
955
+ // The child holds its own copies once spawned; bwrap closes them after
956
+ // mounting, and the host closes these here.
957
+ stdio: ['ignore', 'pipe', 'pipe', ...passFds],
958
+ }, { ownGroup });
959
+ } finally {
960
+ closeHeldPaths(passFds);
961
+ }
953
962
  observeSpawn(proc, onSpawn, controls);
954
963
  let stdout = '';
955
964
  let stderr = '';
@@ -1454,6 +1463,29 @@ const proxyPort = (proxy) => {
1454
1463
  return Number.isInteger(port) && port > 0 ? port : null;
1455
1464
  };
1456
1465
 
1466
+ // F211: the held workspace and its .git, opened and checked, to hand bwrap as
1467
+ // descriptors. Child fd 3 is the workspace and 4 the .git (stdio is 0-2). A
1468
+ // writable workspace needs its .git (checked before this), so failing to hold
1469
+ // it refuses the turn. A read-only one whose .git is missing, a link or
1470
+ // unreadable keeps the path bind for it, which is -try there.
1471
+ // The .git is opened by its path, not under the workspace descriptor: a swap
1472
+ // between the two opens gains nothing, since whoever can make it can already
1473
+ // write that .git.
1474
+ const holdBindSources = (realpath, { write, fdPath }) => {
1475
+ const passFds = [openHeldPath(realpath, { directory: true, ...(fdPath ? { fdPath } : {}) })];
1476
+ const bindFds = { workspace: 3, entries: {} };
1477
+ try {
1478
+ passFds.push(openHeldPath(join(realpath, '.git'), fdPath ? { fdPath } : {}));
1479
+ bindFds.entries['.git'] = 4;
1480
+ } catch (error) {
1481
+ if (write || !['ENOENT', 'ELOOP', 'EACCES'].includes(error?.code)) {
1482
+ closeHeldPaths(passFds);
1483
+ throw error;
1484
+ }
1485
+ }
1486
+ return { passFds, bindFds };
1487
+ };
1488
+
1457
1489
  const prepareArgv = async (innerArgv, ctx) => {
1458
1490
  const env = ctx.environment;
1459
1491
  const claudeEnv = withClaudePath(ctx.claudeEnv);
@@ -1613,12 +1645,13 @@ const prepareArgv = async (innerArgv, ctx) => {
1613
1645
  };
1614
1646
  }
1615
1647
 
1648
+ let bwrap = null;
1616
1649
  if (publicBwrapSandbox || workspaceBwrapSandbox) {
1617
1650
  // The mode is chosen here, so the mechanism is verified here: a missing
1618
1651
  // bwrap must fail the seat's derivation with an actionable message, not
1619
1652
  // every one of its spawns with a bare ENOENT. On a non-Linux
1620
1653
  // host this reports the macOS-only message, same as the wrapper would.
1621
- const bwrap = (ctx._detectBwrap || detectBwrap)();
1654
+ bwrap = (ctx._detectBwrap || detectBwrap)();
1622
1655
  if (!bwrap.available) {
1623
1656
  throw new Error(`${sandboxTrust} Claude agents require bwrap: ${bwrap.error}`);
1624
1657
  }
@@ -1650,39 +1683,53 @@ const prepareArgv = async (innerArgv, ctx) => {
1650
1683
  const { claudeBin, claudeInstall } = resolveClaudeInstall(claudeEnv);
1651
1684
  if (!claudeInstall) throw claudeInstallRefusal(claudeBin);
1652
1685
  const { statePath } = ctx.publicClaudeState;
1653
- const wrapped = wrapArgvWithBwrap([claudeBin, ...innerArgv], env, {
1654
- workspacePath: ctx.cwd,
1655
- // F200: bwrap resolves a bind source when the jail starts, after the
1656
- // check, so the checked realpath is the source, mounted at the path the
1657
- // seat was given.
1658
- workspaceSource: ctx.workspaceRealpath || ctx.cwd,
1659
- workspaceReadOnly: !grants.includes('write'),
1660
- readOnlyWorkspaceEntries: ['.git'],
1661
- homePath: statePath,
1662
- // .claude (the login copy) and tmp are bound again on their own, after
1663
- // the state folder: a mount point cannot be renamed or replaced from
1664
- // inside the jail (EBUSY), so a child, this turn's or a concurrent one's,
1665
- // cannot swap either for a link while the host writes or removes the
1666
- // login there. The state preparation made both real directories.
1667
- writablePaths: [statePath, join(statePath, '.claude'), join(statePath, 'tmp')],
1668
- readOnlyPaths: [
1669
- ctx.mcpConfigDir, commitHooksPath, originalHooksPath,
1670
- ...(ctx.mcpReadDirectories || []),
1671
- ...(ctx.workspaceGit?.readDirectories || []),
1672
- ...(ctx.workspaceGit?.readPaths || []),
1673
- ].filter(Boolean),
1674
- // The binaries the jail runs: claude (a user-local install is outside
1675
- // the default binds, and its link points into a versions folder), the
1676
- // node that runs the stdio MCP servers, and the git the history tool runs.
1677
- optionalReadOnlyPaths: [...new Set([
1678
- dirname(claudeBin), claudeInstall, dirname(process.execPath),
1679
- ctx.workspaceGit ? dirname(ctx.workspaceGit.executable) : null,
1680
- // A claude not found on PATH is left bare and fails at spawn; its
1681
- // dirname is '.', which is not a path to bind.
1682
- ].filter((p) => p && isAbsolute(p)))],
1683
- });
1686
+ const held = bwrap?.bindFd && ctx.workspaceRealpath
1687
+ ? holdBindSources(ctx.workspaceRealpath, { write: grants.includes('write'), fdPath: ctx._fdPath })
1688
+ : { passFds: [], bindFds: {} };
1689
+ let wrapped;
1690
+ try {
1691
+ wrapped = wrapArgvWithBwrap([claudeBin, ...innerArgv], env, {
1692
+ workspacePath: ctx.cwd,
1693
+ // F200: bwrap resolves a bind source when the jail starts, after the
1694
+ // check, so the checked realpath is the source, mounted at the path the
1695
+ // seat was given. F211: where bwrap takes descriptors, the checked
1696
+ // folder is mounted from one, so a swap in the startup window moves
1697
+ // nothing either.
1698
+ workspaceSource: ctx.workspaceRealpath || ctx.cwd,
1699
+ bindFds: held.bindFds,
1700
+ workspaceReadOnly: !grants.includes('write'),
1701
+ readOnlyWorkspaceEntries: ['.git'],
1702
+ homePath: statePath,
1703
+ // .claude (the login copy) and tmp are bound again on their own, after
1704
+ // the state folder: a mount point cannot be renamed or replaced from
1705
+ // inside the jail (EBUSY), so a child, this turn's or a concurrent one's,
1706
+ // cannot swap either for a link while the host writes or removes the
1707
+ // login there. The state preparation made both real directories.
1708
+ writablePaths: [statePath, join(statePath, '.claude'), join(statePath, 'tmp')],
1709
+ readOnlyPaths: [
1710
+ ctx.mcpConfigDir, commitHooksPath, originalHooksPath,
1711
+ ...(ctx.mcpReadDirectories || []),
1712
+ ...(ctx.workspaceGit?.readDirectories || []),
1713
+ ...(ctx.workspaceGit?.readPaths || []),
1714
+ ].filter(Boolean),
1715
+ // The binaries the jail runs: claude (a user-local install is outside
1716
+ // the default binds, and its link points into a versions folder), the
1717
+ // node that runs the stdio MCP servers, and the git the history tool runs.
1718
+ optionalReadOnlyPaths: [...new Set([
1719
+ dirname(claudeBin), claudeInstall, dirname(process.execPath),
1720
+ ctx.workspaceGit ? dirname(ctx.workspaceGit.executable) : null,
1721
+ // A claude not found on PATH is left bare and fails at spawn; its
1722
+ // dirname is '.', which is not a path to bind.
1723
+ ].filter((p) => p && isAbsolute(p)))],
1724
+ });
1725
+ } catch (error) {
1726
+ closeHeldPaths(held.passFds);
1727
+ throw error;
1728
+ }
1684
1729
  // TASK-440 reads the transcript from the HOME the child wrote under.
1685
- return { cmd: wrapped[0], args: wrapped.slice(1), env: claudeEnv, childHome: statePath };
1730
+ return {
1731
+ cmd: wrapped[0], args: wrapped.slice(1), env: claudeEnv, childHome: statePath, passFds: held.passFds,
1732
+ };
1686
1733
  }
1687
1734
  if (sandboxMode === 'bwrap') {
1688
1735
  const claudeBin = resolveClaudePath(claudeEnv);
@@ -2050,11 +2097,14 @@ export default {
2050
2097
  workspacePinDirs,
2051
2098
  claudeEnv,
2052
2099
  };
2053
- const { cmd, args, env, childHome } = await prepareArgv(baseArgs, spawnCtx);
2100
+ const {
2101
+ cmd, args, env, childHome, passFds,
2102
+ } = await prepareArgv(baseArgs, spawnCtx);
2054
2103
  armRelease();
2055
2104
  const stdout = await runClaude({
2056
2105
  cmd,
2057
2106
  args,
2107
+ passFds,
2058
2108
  cwd: ctx.cwd,
2059
2109
  env,
2060
2110
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
@@ -2121,6 +2171,10 @@ export default {
2121
2171
  publicClaudeState,
2122
2172
  publicSkillArgs,
2123
2173
  providerProxyPort: proxyPort(providerProxy),
2174
+ // F200: the retry is the same turn in the same held folder, so it
2175
+ // keeps the checked realpath and the pin record's deny.
2176
+ workspaceRealpath,
2177
+ workspacePinDirs,
2124
2178
  claudeEnv: withProvider(buildClaudeEnv(
2125
2179
  ctx.env,
2126
2180
  publicClaudeState,
@@ -2146,6 +2200,7 @@ export default {
2146
2200
  const stdout = await runClaude({
2147
2201
  cmd: retry.cmd,
2148
2202
  args: retry.args,
2203
+ passFds: retry.passFds,
2149
2204
  cwd: ctx.cwd,
2150
2205
  env: retry.env,
2151
2206
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
@@ -0,0 +1,84 @@
1
+ import { createClient } from './api.js';
2
+ import { CLI } from './cli-hint.js';
3
+
4
+ // F525: the Connect your own agent page's one pasted line carries a connect
5
+ // code, not the agent's lasting key, so the shell history it lands in keeps
6
+ // nothing that still works once the agent has listened. The run trades it for
7
+ // the key on POST /api/agents/runtime/connect-code.
8
+ // The server's codes are 22 characters after the prefix; a little room either
9
+ // way, so a later format isn't refused here as "not a code".
10
+ export const CONNECT_CODE_PATTERN = /^cmc_[A-Za-z0-9_-]{16,64}$/;
11
+
12
+ const PAGE = 'the Connect your own agent page';
13
+
14
+ // One plain line per refusal. `name` is the agent the line was for.
15
+ export const connectCodeRefusalLine = (refusal, {
16
+ name, runName = name, instanceUrl, detail, status,
17
+ } = {}) => {
18
+ switch (refusal) {
19
+ case 'invalid':
20
+ return `That isn't a connect code from ${PAGE}. Copy the line from the page again and paste it whole.`;
21
+ case 'unknown':
22
+ return `This line's connect code has expired: each one works for 30 minutes. Get a new line from ${PAGE}.`;
23
+ case 'used':
24
+ return `${name} has already connected from a computer, so this line's code is spent. `
25
+ + `On that computer, run: ${CLI} agent run ${runName}. To connect it here instead, get a new line from ${PAGE}.`;
26
+ case 'revoked':
27
+ return `${name}'s key has been replaced, so this line no longer works. Get the new line from ${PAGE}.`;
28
+ case 'rate_limited':
29
+ return 'Too many tries with this connect code. Wait a few minutes, then paste the line again.';
30
+ case 'no_fetch':
31
+ return 'This Node is too old to connect: Commonly needs Node 22 or later. '
32
+ + 'Install Node 22 from nodejs.org, then paste the line again.';
33
+ default:
34
+ if (status) {
35
+ return `${instanceUrl} answered HTTP ${status} to the connect code. `
36
+ + `Check the line is the one from ${PAGE}, copy it again, and paste it whole.`;
37
+ }
38
+ return `Couldn't reach ${instanceUrl} to use the connect code${detail ? ` (${detail})` : ''}. `
39
+ + 'Check this computer is online, then paste the line again.';
40
+ }
41
+ };
42
+
43
+ // The line again, from history, on the computer the agent already runs on:
44
+ // the run goes on with the saved key and says why the code wasn't needed, in
45
+ // words, not the server's refusal code. A spent code is deleted on its first
46
+ // refused try, so a later one reads as unknown: that case names both.
47
+ const SAVED_KEY_REASON = {
48
+ used: 'is spent',
49
+ unknown: 'has expired or is spent',
50
+ revoked: 'no longer works',
51
+ rate_limited: 'had too many tries',
52
+ invalid: "isn't a connect code",
53
+ };
54
+ export const savedKeyNote = (refusal) => `this line's connect code ${SAVED_KEY_REASON[refusal] || "couldn't be checked just now"}, `
55
+ + 'so this run uses the key already saved on this computer';
56
+
57
+ const REFUSAL_BY_CODE = {
58
+ invalid_connect_code: 'invalid',
59
+ connect_code_unknown: 'unknown',
60
+ connect_code_used: 'used',
61
+ connect_code_revoked: 'revoked',
62
+ connect_code_rate_limited: 'rate_limited',
63
+ };
64
+
65
+ /**
66
+ * Trade a connect code for the agent's key. Returns `{ token }`, or
67
+ * `{ refusal }` with one of the codes connectCodeRefusalLine knows. Sends no
68
+ * bearer: the code is the credential.
69
+ */
70
+ export const redeemConnectCode = async ({ code, instanceUrl, clientFactory = createClient }) => {
71
+ if (typeof code !== 'string' || !CONNECT_CODE_PATTERN.test(code)) return { refusal: 'invalid' };
72
+ if (typeof fetch !== 'function') return { refusal: 'no_fetch' };
73
+ try {
74
+ const body = await clientFactory({ instance: instanceUrl, token: null })
75
+ .post('/api/agents/runtime/connect-code', { code });
76
+ const token = typeof body?.token === 'string' ? body.token.trim() : '';
77
+ if (!token.startsWith('cm_agent_')) return { refusal: 'unreachable', detail: 'unexpected answer' };
78
+ return { token };
79
+ } catch (err) {
80
+ const known = REFUSAL_BY_CODE[err?.body?.code];
81
+ if (known) return { refusal: known };
82
+ return err?.status ? { refusal: 'unreachable', status: err.status } : { refusal: 'unreachable', detail: err?.message };
83
+ }
84
+ };
@@ -0,0 +1,77 @@
1
+ /**
2
+ * A bind source held by an open descriptor (F211).
3
+ *
4
+ * bwrap resolves a path bind's source when the jail starts, after the host
5
+ * checked it. A seat whose workspace sits inside another writable workspace
6
+ * can have a folder on that path swapped for a link in the window, and the
7
+ * jail is then bound onto the link's target (CodeRabbit on #3527).
8
+ * `--bind-fd` and `--ro-bind-fd` (bubblewrap 0.10.0, backported to 0.6.3)
9
+ * mount an already-open descriptor instead. bwrap also checks that the mount
10
+ * landed on that descriptor's inode, and closes the descriptor before the
11
+ * child runs, so the jail never holds a handle to a host folder.
12
+ *
13
+ * Opening a path still follows links in its parent folders, so the
14
+ * descriptor is checked after the open: the path the kernel reports for it
15
+ * must be the expected realpath. A swap before the open is refused. A swap
16
+ * after it no longer moves anything: the descriptor names the folder that
17
+ * was checked.
18
+ *
19
+ * Linux only, like bwrap. `/proc/self/fd/N` names the open file.
20
+ */
21
+
22
+ import {
23
+ closeSync, constants, fstatSync, openSync, readlinkSync,
24
+ } from 'fs';
25
+
26
+ export const BIND_SOURCE_MOVED = 'bind_source_moved';
27
+
28
+ const procFdPath = (fd) => readlinkSync(`/proc/self/fd/${fd}`);
29
+
30
+ /**
31
+ * Open `path` (the last component never a link) and confirm the descriptor
32
+ * names exactly `path`, a folder or a regular file. Returns the descriptor;
33
+ * the caller closes it once the child has it. Throws the open's own error
34
+ * (ENOENT, ELOOP, ENOTDIR, EACCES) or a `bind_source_moved` error, with
35
+ * nothing left open.
36
+ */
37
+ export const openHeldPath = (path, {
38
+ directory = false,
39
+ open = openSync,
40
+ close = closeSync,
41
+ stat = fstatSync,
42
+ fdPath = procFdPath,
43
+ } = {}) => {
44
+ // O_NONBLOCK: a FIFO swapped in at the path would otherwise hold the open,
45
+ // and the seat's run loop with it, before any turn timer starts. It changes
46
+ // nothing for a folder or a regular file.
47
+ const flags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
48
+ | (directory ? constants.O_DIRECTORY : 0);
49
+ const fd = open(path, flags);
50
+ try {
51
+ const kind = stat(fd);
52
+ if (!kind.isDirectory() && !kind.isFile()) {
53
+ throw Object.assign(
54
+ new Error(`refusing a workspace turn: ${path} is neither a folder nor a file`),
55
+ { code: BIND_SOURCE_MOVED },
56
+ );
57
+ }
58
+ const actual = fdPath(fd);
59
+ if (actual !== path) {
60
+ throw Object.assign(
61
+ new Error(`refusing a workspace turn: ${path} moved while it was being opened for the sandbox`),
62
+ { code: BIND_SOURCE_MOVED },
63
+ );
64
+ }
65
+ return fd;
66
+ } catch (error) {
67
+ close(fd);
68
+ throw error;
69
+ }
70
+ };
71
+
72
+ /** Close every descriptor, ignoring one already closed. */
73
+ export const closeHeldPaths = (fds = [], close = closeSync) => {
74
+ for (const fd of fds) {
75
+ try { close(fd); } catch { /* already closed */ }
76
+ }
77
+ };
@@ -78,6 +78,19 @@ export const bwrapReadRoots = (env) => {
78
78
  // ubuntu run 38982219348). Starting one empty namespace is the real check.
79
79
  const NAMESPACE_PROBE = ['--unshare-all', '--ro-bind', '/', '/', 'true'];
80
80
 
81
+ // F211: `--bind-fd`/`--ro-bind-fd` arrived in bubblewrap 0.10.0 and were
82
+ // backported to 0.6.3, so the version number does not settle it. An older
83
+ // bwrap dies on the unknown option, so it is read from the usage text.
84
+ // Debian 12 ships 0.8.0 and Ubuntu 24.04 0.9.0: both keep the path binds.
85
+ const bindFdSupported = (spawn) => {
86
+ try {
87
+ const res = spawn('bwrap', ['--help'], { encoding: 'utf8', timeout: 10_000 });
88
+ return !res.error && res.status === 0 && /--bind-fd\b/.test(String(res.stdout || ''));
89
+ } catch {
90
+ return false;
91
+ }
92
+ };
93
+
81
94
  const APPARMOR_USERNS_SYSCTL = '/proc/sys/kernel/apparmor_restrict_unprivileged_userns';
82
95
 
83
96
  // Inside a container the sysctl reports the host, and what blocks bwrap is the
@@ -150,7 +163,7 @@ export const detectBwrap = ({
150
163
  + 'On Ubuntu 24.04 and later, AppArmor restricts the unprivileged user namespaces it needs.',
151
164
  };
152
165
  }
153
- return { available: true, path: 'bwrap' };
166
+ return { available: true, path: 'bwrap', bindFd: bindFdSupported(spawn) };
154
167
  } catch (err) {
155
168
  return { available: false, error: `bwrap detection failed: ${err.message}` };
156
169
  }
@@ -318,7 +331,23 @@ export const wrapArgvWithBwrap = (innerArgv, env, opts = {}) => {
318
331
  if (!isAbsolute(workspaceSource)) {
319
332
  throw new Error('wrapArgvWithBwrap opts.workspaceSource must be an absolute path');
320
333
  }
321
- flags.push(opts.workspaceReadOnly ? '--ro-bind' : '--bind', workspaceSource, opts.workspacePath);
334
+ // F211: with descriptors (the caller opened and checked the source, and
335
+ // passes it at this child fd), bwrap mounts the open folder, so a swap of
336
+ // the path after the check cannot move the mount.
337
+ const fds = opts.bindFds || {};
338
+ const childFd = (value) => {
339
+ if (value === undefined || value === null) return null;
340
+ if (!Number.isInteger(value) || value < 3) {
341
+ throw new Error('wrapArgvWithBwrap opts.bindFds entries must be child descriptors of 3 or more');
342
+ }
343
+ return String(value);
344
+ };
345
+ const workspaceFd = childFd(fds.workspace);
346
+ if (workspaceFd) {
347
+ flags.push(opts.workspaceReadOnly ? '--ro-bind-fd' : '--bind-fd', workspaceFd, opts.workspacePath);
348
+ } else {
349
+ flags.push(opts.workspaceReadOnly ? '--ro-bind' : '--bind', workspaceSource, opts.workspacePath);
350
+ }
322
351
  // Entries held read-only inside a writable workspace (its .git). Bound after
323
352
  // the workspace so they land on top of it. In a writable workspace a missing
324
353
  // entry cannot be protected — the child could create it, and a planted
@@ -328,8 +357,13 @@ export const wrapArgvWithBwrap = (innerArgv, env, opts = {}) => {
328
357
  if (!entry || isAbsolute(entry) || entry.split(/[\\/]/).includes('..')) {
329
358
  throw new Error('wrapArgvWithBwrap opts.readOnlyWorkspaceEntries entries must be relative names inside the workspace');
330
359
  }
331
- flags.push(opts.workspaceReadOnly ? '--ro-bind-try' : '--ro-bind',
332
- join(workspaceSource, entry), join(opts.workspacePath, entry));
360
+ const entryFd = childFd(fds.entries?.[entry]);
361
+ if (entryFd) {
362
+ flags.push('--ro-bind-fd', entryFd, join(opts.workspacePath, entry));
363
+ } else {
364
+ flags.push(opts.workspaceReadOnly ? '--ro-bind-try' : '--ro-bind',
365
+ join(workspaceSource, entry), join(opts.workspacePath, entry));
366
+ }
333
367
  }
334
368
  flags.push('--chdir', opts.workspacePath);
335
369
  flags.push('--setenv', 'HOME', opts.homePath || opts.workspacePath);