@commonlyai/cli 0.1.386 → 0.1.387

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.386",
3
+ "version": "0.1.387",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -58,7 +58,9 @@ import { spawn as childSpawn, spawnSync } from 'child_process';
58
58
  import {
59
59
  createHash, randomBytes, randomUUID, timingSafeEqual,
60
60
  } from 'crypto';
61
- import { accessSync, constants, realpathSync } from 'fs';
61
+ import {
62
+ accessSync, constants, readdirSync, realpathSync,
63
+ } from 'fs';
62
64
  import {
63
65
  chmod,
64
66
  lstat,
@@ -94,6 +96,7 @@ import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from '../sandbox/mode.
94
96
  import { UNSANDBOXED_FLAG } from '../sandbox/host-check.js';
95
97
  import {
96
98
  publicClaudeStateRoot,
99
+ resolveHostReadDirectories,
97
100
  wrapArgvWithSeatbelt,
98
101
  } from '../sandbox/seatbelt.js';
99
102
  import {
@@ -143,6 +146,17 @@ const PARALLEL_READS_CUE = 'Parallel reads: when a row needs several files or so
143
146
  const WORK_CUES = [PARALLEL_READS_CUE, ROW_SLICING_CUE, BACKGROUND_PROCESS_CUE];
144
147
  const RUNTIME_CREDENTIAL_PLACEHOLDER = '${COMMONLY_AGENT_TOKEN}';
145
148
 
149
+ // A workspace seat's sandbox.filesystem.read-outside, with `~` expanded the way
150
+ // bwrap.js expands it. Anything still relative is refused by the profile.
151
+ const workspaceReadOutside = (env) => {
152
+ const declared = env?.sandbox?.filesystem?.['read-outside'];
153
+ if (!Array.isArray(declared)) return [];
154
+ return declared.map((p) => {
155
+ if (p === '~') return homedir();
156
+ return typeof p === 'string' && p.startsWith('~/') ? join(homedir(), p.slice(2)) : p;
157
+ });
158
+ };
159
+
146
160
  const QUOTE_SHELL_ARGUMENT = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
147
161
 
148
162
  // The helper takes the token from one of two places. With a socket path and a
@@ -647,12 +661,43 @@ const permissionPath = (path, platform) => (platform === 'win32'
647
661
  // The tools that read or write the seat's agent-wide memory.
648
662
  const MEMORY_TOOLS = Object.freeze(['commonly_read_agent_memory', 'commonly_write_agent_memory', 'commonly_save_my_memory']);
649
663
 
650
- const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
664
+ export const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
651
665
  trust, allow = [], memoryWithheld = false, ownerWoken = false, platform = process.platform, home: homeOverride = null,
652
666
  noShell = false,
667
+ // F122: a workspace seat's host read folders, already checked and resolved
668
+ // (resolveHostReadDirectories). The jail is the boundary; this lets the
669
+ // seat's Read, Grep and Glob reach them, which `Read(./**)` alone does not.
670
+ hostReads = [],
653
671
  } = {}) => {
654
672
  const home = homeOverride || homedir();
655
673
  const deny = (sub) => absoluteToolDeny(permissionPath(join(home, sub), platform));
674
+ const hostReadAllows = hostReads.map((dir) => absoluteToolDeny(permissionPath(dir, platform)));
675
+ // Claude Code applies a deny before any allow, so a grant inside ~/.commonly
676
+ // (only ~/.commonly/logs passes the check) would be refused by the
677
+ // ~/.commonly deny. Then that deny becomes one per other entry in the folder.
678
+ // An entry created after the spawn is not named here; the jail still
679
+ // refuses it, as it refuses everything not granted.
680
+ const commonlyHome = join(home, '.commonly');
681
+ const folded = (p) => p.toLowerCase();
682
+ const grantsInsideCommonly = hostReads.some((dir) => folded(dir).startsWith(`${folded(commonlyHome)}/`));
683
+ const commonlyDenies = () => {
684
+ if (!grantsInsideCommonly) return [deny('.commonly')];
685
+ try {
686
+ return readdirSync(commonlyHome)
687
+ .filter((name) => !hostReads.some((dir) => {
688
+ const entry = folded(join(commonlyHome, name));
689
+ return folded(dir) === entry || folded(dir).startsWith(`${entry}/`);
690
+ }))
691
+ // A file such as admin-token is matched by its own name, a folder by
692
+ // what is under it: each entry is denied both ways.
693
+ .flatMap((name) => {
694
+ const entry = permissionPath(join(commonlyHome, name), platform);
695
+ return [`Read(/${entry})`, `Read(/${entry}/**)`];
696
+ });
697
+ } catch {
698
+ return [deny('.commonly')];
699
+ }
700
+ };
656
701
  // `allow` is already narrowed to a workspace seat's grants (workspaceGrants).
657
702
  // With no OS jail (native Windows, --unsandboxed) a shell would run
658
703
  // with the user's whole access and could read the seat's own token from its
@@ -663,7 +708,7 @@ const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
663
708
  .filter((tool) => !(noShell && SHELL_TOOLS.has(tool)))
664
709
  .map((tool) => (noShell && (tool === 'Edit' || tool === 'Write') ? `${tool}(./**)` : tool));
665
710
  const deniedReads = [
666
- deny('.commonly'),
711
+ ...commonlyDenies(),
667
712
  deny('.claude'),
668
713
  deny('.codex'),
669
714
  deny('.ssh'),
@@ -716,7 +761,7 @@ const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
716
761
  '--strict-mcp-config',
717
762
  '--no-chrome',
718
763
  '--permission-mode', 'dontAsk',
719
- '--allowedTools', 'Read(./**)', ...granted, ...mcpToolPatterns,
764
+ '--allowedTools', 'Read(./**)', ...hostReadAllows, ...granted, ...mcpToolPatterns,
720
765
  '--disallowedTools', ...PUBLIC_DENIED_TOOLS.filter((tool) => !granted.some((g) => g === tool || g.startsWith(`${tool}(`))),
721
766
  ...deniedReads, ...toolDenies,
722
767
  ];
@@ -1597,10 +1642,15 @@ const prepareArgv = async (innerArgv, ctx) => {
1597
1642
  if (!ctx.publicClaudeState) {
1598
1643
  throw new Error('public Claude state was not prepared before argv construction');
1599
1644
  }
1645
+ // F122: checked and resolved once; the policy and the profile get the same list.
1646
+ const hostReads = sandboxTrust === 'workspace'
1647
+ ? resolveHostReadDirectories(workspaceReadOutside(env))
1648
+ : [];
1600
1649
  innerArgv = [
1601
1650
  ...innerArgv,
1602
1651
  ...buildPublicClaudePolicyArgs(allowedPatterns, {
1603
1652
  trust: sandboxTrust, allow: grants, memoryWithheld: ctx.memoryWithheld === true, ownerWoken: ctx.ownerWoken,
1653
+ hostReads,
1604
1654
  }),
1605
1655
  ...(ctx.publicSkillArgs || []),
1606
1656
  ];
@@ -1644,6 +1694,10 @@ const prepareArgv = async (innerArgv, ctx) => {
1644
1694
  ...(ctx.workspaceGit?.readDirectories || []),
1645
1695
  ],
1646
1696
  readOnlyPaths: ctx.workspaceGit?.readPaths || [],
1697
+ // F122: a workspace seat reads the host folders it names, as it does
1698
+ // under bwrap on Linux, so an Ops-type seat can read the logs it watches
1699
+ // without running unconfined. A public seat names none: strangers drive it.
1700
+ hostReadDirectories: hostReads,
1647
1701
  });
1648
1702
  return {
1649
1703
  cmd: wrapped[0],
@@ -23,7 +23,7 @@ import { spawnSync } from 'child_process';
23
23
  import { lstatSync, realpathSync } from 'fs';
24
24
  import { homedir } from 'os';
25
25
  import {
26
- basename, dirname, isAbsolute, join, resolve,
26
+ basename, dirname, isAbsolute, join, relative, resolve,
27
27
  } from 'path';
28
28
 
29
29
  const SANDBOX_EXEC = '/usr/bin/sandbox-exec';
@@ -480,6 +480,100 @@ export const detectSeatbelt = () => {
480
480
  }
481
481
  };
482
482
 
483
+ // F122: which host folders a workspace seat may read through its
484
+ // sandbox.filesystem.read-outside. An allowlist, not a list of where
485
+ // credentials live: such a list lags every new token file (an Opus review found
486
+ // eleven under ~/.commonly that one missed). Inside the home folder:
487
+ // - a folder whose first name under home starts with a dot is refused, except
488
+ // HOST_READ_DOT_ALLOW (the CLI's logs);
489
+ // - ~/Library is refused (keychains, browser and app data);
490
+ // - the home folder itself, and any folder that holds it (`/`, /Users), are
491
+ // refused.
492
+ // Anything else in home (a project tree) is admitted read-only, with the
493
+ // workspace's own credential denies (.env*, .commonly, .codex, .npmrc, .yarnrc)
494
+ // applied beneath it. Outside home only HOST_READ_SYSTEM_ALLOW is admitted: the
495
+ // temp folders hold every seat's per-turn runtime token (same uid, so their
496
+ // 0700 mode is no fence), and /System/Volumes/Data firmlink spellings of home
497
+ // are refused with everything else not on the list (second Opus review).
498
+ //
499
+ // Paths are compared canonically and case-folded. APFS is case-insensitive and
500
+ // so is Seatbelt's subpath match, while path.relative and the JS realpathSync
501
+ // keep the case they were given: `~/.SSH` would otherwise pass a check for
502
+ // `.ssh` and still read ~/.ssh.
503
+ export const HOST_READ_DOT_ALLOW = Object.freeze(['.commonly/logs']);
504
+ export const HOST_READ_SYSTEM_ALLOW = Object.freeze(['/var/log', '/private/var/log', '/Library/Logs']);
505
+
506
+ // The real path, with the real case, of the longest prefix that exists, plus
507
+ // the rest as given. Resolved once: the result is both checked and granted.
508
+ const canonicalPath = (path) => {
509
+ const absolute = resolve(path);
510
+ let existing = absolute;
511
+ const rest = [];
512
+ for (;;) {
513
+ try {
514
+ return join(realpathSync.native(existing), ...rest);
515
+ } catch {
516
+ const parent = dirname(existing);
517
+ if (parent === existing) return absolute;
518
+ rest.unshift(basename(existing));
519
+ existing = parent;
520
+ }
521
+ }
522
+ };
523
+
524
+ const foldedWithin = (outer, inner) => {
525
+ const rel = relative(outer.toLowerCase(), inner.toLowerCase());
526
+ return rel === '' || (rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel));
527
+ };
528
+
529
+ // A dot folder or dotfile anywhere along the path, not only directly under
530
+ // home: ~/Projects/repo/.commonly is a token folder too (CodeRabbit on #4111).
531
+ // The one exception is inside HOST_READ_DOT_ALLOW.
532
+ const dotComponent = (canonical, home) => {
533
+ if (HOST_READ_DOT_ALLOW.some((allowed) => foldedWithin(join(home, allowed), canonical))) {
534
+ const allowed = HOST_READ_DOT_ALLOW.find((a) => foldedWithin(join(home, a), canonical));
535
+ const below = relative(join(home, allowed).toLowerCase(), canonical.toLowerCase());
536
+ return below.split('/').find((name) => name.startsWith('.')) || null;
537
+ }
538
+ return canonical.split('/').find((name) => name.startsWith('.')) || null;
539
+ };
540
+
541
+ const hostReadRefusal = (canonical, home) => {
542
+ if (foldedWithin(canonical, home)) return 'it holds your home folder';
543
+ const dot = dotComponent(canonical, home);
544
+ if (dot) {
545
+ return `${dot} is a dot folder or dotfile, and those are not readable from a seat `
546
+ + `(only ${HOST_READ_DOT_ALLOW.map((a) => `~/${a}`).join(', ')} is)`;
547
+ }
548
+ if (!foldedWithin(home, canonical)) {
549
+ return HOST_READ_SYSTEM_ALLOW.some((allowed) => foldedWithin(allowed, canonical))
550
+ ? null
551
+ : `outside your home folder only ${HOST_READ_SYSTEM_ALLOW.join(', ')} are readable from a seat`;
552
+ }
553
+ const rel = relative(home.toLowerCase(), canonical.toLowerCase());
554
+ const [first] = rel.split('/');
555
+ if (first === 'library') return '~/Library holds keychains and app data';
556
+ if (first.startsWith('.')
557
+ && !HOST_READ_DOT_ALLOW.some((allowed) => foldedWithin(join(home, allowed), canonical))) {
558
+ return `the folders under ~/${first.split('/')[0]} are not readable from a seat `
559
+ + `(of the dot folders, only ${HOST_READ_DOT_ALLOW.map((a) => `~/${a}`).join(', ')} is)`;
560
+ }
561
+ return null;
562
+ };
563
+
564
+ // Each entry resolved once, refused on the first that fails, in the order given.
565
+ export const resolveHostReadDirectories = (entries, home = homedir()) => {
566
+ const canonicalHome = canonicalPath(home);
567
+ return entries.map((entry) => {
568
+ const canonical = canonicalPath(entry);
569
+ const reason = hostReadRefusal(canonical, canonicalHome);
570
+ if (reason) {
571
+ throw new Error(`refusing sandbox.filesystem.read-outside ${entry}: ${reason}.`);
572
+ }
573
+ return canonical;
574
+ });
575
+ };
576
+
483
577
  export const buildSeatbeltProfile = ({
484
578
  workspacePath,
485
579
  workspaceAccess = 'write',
@@ -489,6 +583,14 @@ export const buildSeatbeltProfile = ({
489
583
  executablePaths = [],
490
584
  readOnlyPaths = [],
491
585
  readOnlyDirectories = [],
586
+ // F122: host folders a workspace seat names in sandbox.filesystem.read-outside,
587
+ // admitted read-only. Unlike readOnlyDirectories (folders the adapter itself
588
+ // prepared), these come from the seat's spec, which the server can write, so
589
+ // each passes resolveHostReadDirectories first and the turn is refused
590
+ // otherwise.
591
+ hostReadDirectories = [],
592
+ // The home folder those rules are judged against. Tests pass a temp one.
593
+ hostReadHome = homedir(),
492
594
  loopbackNetworkPorts = [],
493
595
  allowClaudeRuntimeAccess = false,
494
596
  // 'open' (the default) or 'loopback': only the listed loopback ports.
@@ -533,6 +635,8 @@ export const buildSeatbeltProfile = ({
533
635
  for (const path of denyWritePaths) assertAbsolutePath(path, 'denyWritePaths entry');
534
636
  for (const path of readOnlyPaths) assertAbsolutePath(path, 'readOnlyPaths entry');
535
637
  for (const path of readOnlyDirectories) assertAbsolutePath(path, 'readOnlyDirectories entry');
638
+ for (const path of hostReadDirectories) assertAbsolutePath(path, 'hostReadDirectories entry');
639
+ const grantedHostReads = [...new Set(resolveHostReadDirectories(hostReadDirectories, hostReadHome))];
536
640
  for (const port of loopbackNetworkPorts) {
537
641
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
538
642
  throw new Error('Seatbelt loopbackNetworkPorts entries must be valid TCP ports');
@@ -582,7 +686,10 @@ export const buildSeatbeltProfile = ({
582
686
  const resolvedState = pinnedRealpath(statePath, 'state folder');
583
687
  const resolvedMcpConfig = mcpConfigDir ? realpathOrSelf(mcpConfigDir) : null;
584
688
  const resolvedReadOnlyPaths = [...new Set(readOnlyPaths.map(realpathOrSelf))];
585
- const resolvedReadOnlyDirectories = [...new Set(readOnlyDirectories.map(realpathOrSelf))];
689
+ const resolvedReadOnlyDirectories = [...new Set([
690
+ ...readOnlyDirectories.map(realpathOrSelf),
691
+ ...grantedHostReads,
692
+ ])];
586
693
  const executables = [...new Set(
587
694
  [resolvedExecutable, process.execPath, ...executablePaths]
588
695
  .filter(Boolean)
@@ -619,6 +726,12 @@ export const buildSeatbeltProfile = ({
619
726
  `(allow file-read* file-test-existence ${subpath(path)})`,
620
727
  `(allow file-read-metadata file-test-existence (path-ancestors "${escapeSbplString(path)}"))`,
621
728
  ].join('\n'))).join('\n');
729
+ // The adapter's own read-only inputs, without the host read grants.
730
+ const adapterReadOnlyRules = resolvedReadOnlyPaths.map((path) => (
731
+ `(allow file-read* file-test-existence ${literal(path)})`
732
+ )).concat(resolvedReadOnlyDirectories.filter((path) => !grantedHostReads.includes(path)).map((path) => (
733
+ `(allow file-read* file-test-existence ${subpath(path)})`
734
+ ))).join('\n');
622
735
  // A symlinked entry is held at both its name and its target, so the write
623
736
  // cannot land through whichever path the link resolves to.
624
737
  const readOnlyWorkspaceRules = [...new Set(readOnlyWorkspaceEntries.flatMap((entry) => {
@@ -654,6 +767,16 @@ export const buildSeatbeltProfile = ({
654
767
  loopbackNetworkRules,
655
768
  mcpRule,
656
769
  readOnlyRules,
770
+ // Beneath a host read folder, every dot folder and dotfile is denied, the
771
+ // same rule its request passed: a project tree holds other repos' .env
772
+ // files, .commonly token folders, .ssh keys and .aws credentials. One rule
773
+ // on the leading dot covers every name, in any case (CodeRabbit on #4129).
774
+ ...grantedHostReads.map((dir) => `(deny file-read* file-write* ${regexUnder(dir, '\\.[^/]*(/.*)?$')})`),
775
+ // Later rules win, so a grant that holds the workspace, or a folder the
776
+ // adapter itself prepared, would hide its .git and dotfiles. Those allows
777
+ // are stated again here, and the workspace's credential denies follow them
778
+ // (CodeRabbit on #4111).
779
+ ...(grantedHostReads.length ? [workspaceRule, adapterReadOnlyRules] : []),
657
780
  // The workspace is intentionally readable, but credential-like nested
658
781
  // paths are not. Explicit deny wins over the broad workspace allow.
659
782
  `(deny file-read* file-write* ${subpath(join(resolvedWorkspace, '.commonly'))})`,