@commonlyai/cli 0.1.258 → 0.1.259

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.258",
3
+ "version": "0.1.259",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -234,6 +234,92 @@ const statOrNull = async (path) => {
234
234
  }
235
235
  };
236
236
 
237
+ // A subfolder of a seat's state, which the confined child can also write: it
238
+ // must be a real directory (created 0700 if absent), never a link the child
239
+ // left. The chmod goes through a handle opened with O_NOFOLLOW|O_DIRECTORY, so
240
+ // a link swapped in after the check (Seatbelt has no PID namespace, and a
241
+ // process a prior turn left can still run) fails the open instead of being
242
+ // followed out of the folder. `_afterCheck` is a test seam for that swap.
243
+ export const ensurePrivateDir = async (dir, { _afterCheck } = {}) => {
244
+ const refuse = () => new Error(`refusing Claude state path that is not a directory: ${dir}`);
245
+ const existing = await statOrNull(dir);
246
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) throw refuse();
247
+ if (!existing) await mkdir(dir, { mode: 0o700 });
248
+ await _afterCheck?.();
249
+ let handle;
250
+ try {
251
+ handle = await open(dir, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY);
252
+ } catch (err) {
253
+ if (['ELOOP', 'ENOTDIR', 'ENOENT'].includes(err?.code)) throw refuse();
254
+ throw err;
255
+ }
256
+ try {
257
+ if (!(await handle.stat()).isDirectory()) throw refuse();
258
+ await handle.chmod(0o700);
259
+ } finally {
260
+ await handle.close();
261
+ }
262
+ };
263
+
264
+ // The seat's state folder itself. A Seatbelt rule that lets the child write
265
+ // below a folder lets it write the folder too, so a child can remove it and
266
+ // leave a link in its place. Every later step of the next turn walks below this
267
+ // path (chmod, tmp, Library, the Keychains link, the auth metadata), so a link
268
+ // here refuses the turn before any of them runs. The parent is made by path;
269
+ // the folder is made and chmodded through a handle that does not follow a link.
270
+ const ensureStateFolder = async (statePath) => {
271
+ await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });
272
+ const existing = await statOrNull(statePath);
273
+ if (existing?.isSymbolicLink()) {
274
+ throw new Error(`refusing Claude state folder that is a symbolic link: ${statePath}. `
275
+ + 'A confined turn can replace its own state folder; remove the link (it is the seat\'s state, '
276
+ + 'not the place it points to) and run the turn again, which recreates the folder.');
277
+ }
278
+ await ensurePrivateDir(statePath);
279
+ };
280
+
281
+ // Removes files the host put in a child-writable folder: the one named, or
282
+ // every name `match` accepts. The folder is checked first, and nothing is
283
+ // removed if the child swapped it for a link (to the person's own ~/.claude,
284
+ // say). The check is a path check, so it holds only while no confined process
285
+ // can swap the folder: on bwrap the folders the host removes from (.claude)
286
+ // are mount points inside every jail of the seat, which the child cannot
287
+ // rename or replace (EBUSY), and between turns no child of the seat runs.
288
+ const removePrivateFile = async (dir, name, { match } = {}) => {
289
+ const dirStat = await statOrNull(dir);
290
+ if (!dirStat) return;
291
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
292
+ // eslint-disable-next-line no-console
293
+ console.warn(`[claude] not removing ${name}: ${dir} is no longer a directory`);
294
+ return;
295
+ }
296
+ const names = match ? (await readdir(dir)).filter(match) : [name];
297
+ for (const entry of names) {
298
+ try {
299
+ await rm(join(dir, entry), { force: true });
300
+ } catch (err) {
301
+ // A directory under the name is the child's, not a copy the host wrote:
302
+ // it is left, and the rest of the removal goes on.
303
+ if (!['ERR_FS_EISDIR', 'EISDIR'].includes(err?.code)) throw err;
304
+ // eslint-disable-next-line no-console
305
+ console.warn(`[claude] not removing ${join(dir, entry)}: it is not a file`);
306
+ }
307
+ }
308
+ };
309
+
310
+ // The staged name `replacePrivateFile` writes beside its target.
311
+ const stagedName = (name) => `.${name}.${randomUUID()}.tmp`;
312
+ const STAGED_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
313
+ const isStagedCopyOf = (name) => (entry) => entry.startsWith(`.${name}.`) && entry.endsWith('.tmp')
314
+ && STAGED_UUID.test(entry.slice(name.length + 2, -4));
315
+
316
+ // The login copy and any staged copy of it a failed or killed turn left: both
317
+ // hold the access token.
318
+ const removeLoginCopy = async (configDir) => {
319
+ await removePrivateFile(configDir, '.credentials.json');
320
+ await removePrivateFile(configDir, '.credentials.json', { match: isStagedCopyOf('.credentials.json') });
321
+ };
322
+
237
323
  // The non-secret account metadata Claude needs from ~/.claude.json to find its
238
324
  // login, and nothing else from that file.
239
325
  const claudeAuthMetadata = async () => {
@@ -275,11 +361,12 @@ const preparePublicClaudeState = async (ctx, { keychain = true } = {}) => {
275
361
  const stateKeychains = join(stateLibrary, 'Keychains');
276
362
  const operatorKeychains = join(homedir(), 'Library', 'Keychains');
277
363
 
278
- await mkdir(tmpPath, { recursive: true, mode: 0o700 });
279
- await mkdir(stateLibrary, { recursive: true, mode: 0o700 });
280
- await chmod(statePath, 0o700);
281
- await chmod(tmpPath, 0o700);
282
- await chmod(stateLibrary, 0o700);
364
+ // The jail writes inside this folder, so the folder or a subfolder may be a
365
+ // link a prior turn left: each is checked before the host chmods or links
366
+ // inside it.
367
+ await ensureStateFolder(statePath);
368
+ await ensurePrivateDir(tmpPath);
369
+ await ensurePrivateDir(stateLibrary);
283
370
 
284
371
  // `/usr/bin/security` resolves the default login keychain relative to HOME.
285
372
  // Keep HOME isolated while pointing that one standard location at the
@@ -302,29 +389,31 @@ const preparePublicClaudeState = async (ctx, { keychain = true } = {}) => {
302
389
  await symlink(operatorKeychains, stateKeychains);
303
390
  }
304
391
 
305
- await writeFile(
306
- configPath,
307
- `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`,
308
- { encoding: 'utf8', mode: 0o600 },
309
- );
310
- await chmod(configPath, 0o600);
392
+ // Staged and renamed, as on bwrap: a link at this name is replaced, never
393
+ // written through (F153).
394
+ await replacePrivateFile(statePath, '.claude.json', `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`);
311
395
  return { statePath, tmpPath, configPath };
312
396
  };
313
397
 
314
398
  // Writes a 0600 file into a directory the confined child can also write. The
315
399
  // directory must still be a real directory, and the file is written beside the
316
400
  // target and renamed over it, so a symlink the child left at either name is
317
- // replaced, never followed into another of the person's files.
318
- const replacePrivateFile = async (dir, name, content) => {
401
+ // replaced, never followed into another of the person's files. The directory
402
+ // check is a path check: it holds while no confined process can swap the
403
+ // directory, which on bwrap the .claude mount point inside the jail ensures.
404
+ // A failed write or rename removes the staged copy, which holds the content.
405
+ // `_writeFile` is a test seam.
406
+ export const replacePrivateFile = async (dir, name, content, { _writeFile = writeFile } = {}) => {
319
407
  const dirStat = await statOrNull(dir);
320
408
  if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
321
409
  throw new Error(`refusing to write Claude state into a non-directory: ${dir}`);
322
410
  }
323
411
  const target = join(dir, name);
324
- const staged = join(dir, `.${name}.${randomUUID()}.tmp`);
325
- await writeFile(staged, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
412
+ const staged = join(dir, stagedName(name));
326
413
  try {
327
- await chmod(staged, 0o600);
414
+ // `wx` creates the file 0600 or fails; no chmod by path after it, which
415
+ // would follow a link a concurrent child swapped in for the staged name.
416
+ await _writeFile(staged, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
328
417
  await rename(staged, target);
329
418
  } catch (err) {
330
419
  await rm(staged, { force: true });
@@ -382,7 +471,7 @@ const releaseLoginTurn = async (marker, loginPath) => {
382
471
  else await rm(join(dir, name), { force: true });
383
472
  }
384
473
  if (!live) {
385
- await rm(loginPath, { force: true });
474
+ await removeLoginCopy(dirname(loginPath));
386
475
  // Only an empty folder goes: a turn registering at this moment keeps it.
387
476
  try { await rmdir(dir); } catch { /* not empty, or already gone */ }
388
477
  }
@@ -446,7 +535,7 @@ const carryClaudeLogin = async (env, configDir, { accessOnly = false, mustOutlas
446
535
  handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
447
536
  } catch (err) {
448
537
  if (err?.code === 'ENOENT') {
449
- await rm(join(configDir, '.credentials.json'), { force: true });
538
+ await removeLoginCopy(configDir);
450
539
  return null;
451
540
  }
452
541
  if (err?.code === 'ELOOP') throw refuse();
@@ -483,22 +572,14 @@ const prepareWorkspaceBwrapClaudeState = async (ctx, { login = 'carry', seat = '
483
572
  const statePath = bwrapClaudeStatePath(ctx, seat);
484
573
  const tmpPath = join(statePath, 'tmp');
485
574
  const configDir = join(statePath, '.claude');
486
- await mkdir(statePath, { recursive: true, mode: 0o700 });
487
- await chmod(statePath, 0o700);
488
- for (const dir of [tmpPath, configDir]) {
489
- const existing = await statOrNull(dir);
490
- if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) {
491
- throw new Error(`refusing Claude state path that is not a directory: ${dir}`);
492
- }
493
- if (!existing) await mkdir(dir, { mode: 0o700 });
494
- await chmod(dir, 0o700);
495
- }
575
+ await ensureStateFolder(statePath);
576
+ for (const dir of [tmpPath, configDir]) await ensurePrivateDir(dir);
496
577
 
497
578
  const configPath = await replacePrivateFile(
498
579
  statePath, '.claude.json', `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`,
499
580
  );
500
581
  if (login === 'none') {
501
- await rm(join(configDir, '.credentials.json'), { force: true });
582
+ await removeLoginCopy(configDir);
502
583
  return { statePath, tmpPath, configPath, loginPath: null };
503
584
  }
504
585
  const loginPath = await carryClaudeLogin(ctx.env, configDir, login === 'access-only'
@@ -1440,7 +1521,12 @@ const prepareArgv = async (innerArgv, ctx) => {
1440
1521
  workspaceReadOnly: !grants.includes('write'),
1441
1522
  readOnlyWorkspaceEntries: ['.git'],
1442
1523
  homePath: statePath,
1443
- writablePaths: [statePath],
1524
+ // .claude (the login copy) and tmp are bound again on their own, after
1525
+ // the state folder: a mount point cannot be renamed or replaced from
1526
+ // inside the jail (EBUSY), so a child, this turn's or a concurrent one's,
1527
+ // cannot swap either for a link while the host writes or removes the
1528
+ // login there. The state preparation made both real directories.
1529
+ writablePaths: [statePath, join(statePath, '.claude'), join(statePath, 'tmp')],
1444
1530
  readOnlyPaths: [
1445
1531
  ctx.mcpConfigDir, commitHooksPath, originalHooksPath,
1446
1532
  ...(ctx.mcpReadDirectories || []),
@@ -1870,6 +1956,12 @@ export default {
1870
1956
  stats: claudeRunStats(stdout),
1871
1957
  };
1872
1958
  }
1959
+ // F153: a Seatbelt seat with no key signs in only through the keychain.
1960
+ // When that fails, say how to give it a key instead, as bwrap does.
1961
+ if (publicNativeSandbox && !providerProxy && /not logged in/i.test(String(err?.message))) {
1962
+ err.message = `${err.message}. Sign in with \`claude\` in your own terminal on this Mac, `
1963
+ + 'or set ANTHROPIC_API_KEY (in the service env for daemon seats)';
1964
+ }
1873
1965
  throw err;
1874
1966
  } finally {
1875
1967
  if (mcpConfig?.dir) {
@@ -1880,7 +1972,7 @@ export default {
1880
1972
  // turn of the agent to finish removes it.
1881
1973
  if (publicBwrapSandbox && !workspaceBwrapSandbox && publicClaudeState?.loginPath) {
1882
1974
  if (loginTurn) await releaseLoginTurn(loginTurn, publicClaudeState.loginPath);
1883
- else await rm(publicClaudeState.loginPath, { force: true });
1975
+ else await removeLoginCopy(dirname(publicClaudeState.loginPath));
1884
1976
  }
1885
1977
  }
1886
1978
  },