@commonlyai/cli 0.1.348 → 0.1.350

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.348",
3
+ "version": "0.1.350",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -55,7 +55,9 @@ import { describeTurnReap, markTurn, turnReapEnabled } from '@commonlyai/seats/t
55
55
  import { requireSeatModel, seatModelRequired } from './seat-model.js';
56
56
  import { claudeRunStats } from '../reply-receipt.js';
57
57
  import { spawn as childSpawn, spawnSync } from 'child_process';
58
- import { createHash, randomUUID } from 'crypto';
58
+ import {
59
+ createHash, randomBytes, randomUUID, timingSafeEqual,
60
+ } from 'crypto';
59
61
  import { accessSync, constants, realpathSync } from 'fs';
60
62
  import {
61
63
  chmod,
@@ -73,6 +75,7 @@ import {
73
75
  unlink,
74
76
  writeFile,
75
77
  } from 'fs/promises';
78
+ import { createServer } from 'net';
76
79
  import { homedir, tmpdir } from 'os';
77
80
  import {
78
81
  delimiter, dirname, isAbsolute, join,
@@ -140,12 +143,33 @@ const RUNTIME_CREDENTIAL_PLACEHOLDER = '${COMMONLY_AGENT_TOKEN}';
140
143
 
141
144
  const QUOTE_SHELL_ARGUMENT = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
142
145
 
146
+ // The helper takes the token from one of two places. With a socket path and a
147
+ // key file as its second and third arguments (a public seat, F461), it sends
148
+ // the key and the adapter, which holds the token in memory for the turn,
149
+ // answers with the token; the credential file can then go once the stdio
150
+ // servers have read it. Otherwise it reads the per-spawn file.
143
151
  const HEADER_TOKEN_HELPER_SOURCE = `import { readFileSync } from 'node:fs';
144
-
145
- const credentialFile = process.env.${CREDENTIAL_FILE_VAR};
146
- if (!credentialFile) throw new Error('missing ${CREDENTIAL_FILE_VAR}');
147
- const token = readFileSync(credentialFile, 'utf8').trim();
148
- if (!token) throw new Error('empty ${CREDENTIAL_FILE_VAR}');
152
+ import { createConnection } from 'node:net';
153
+
154
+ const fromChannel = (path, key) => new Promise((resolve, reject) => {
155
+ const chunks = [];
156
+ const socket = createConnection({ path }, () => socket.write(key + '\\n'));
157
+ socket.setTimeout(10000, () => socket.destroy(new Error('the header credential channel did not answer')));
158
+ socket.on('data', (chunk) => chunks.push(chunk));
159
+ socket.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
160
+ socket.on('error', reject);
161
+ });
162
+ const channel = process.argv[3];
163
+ let token;
164
+ if (channel) {
165
+ token = (await fromChannel(channel, readFileSync(process.argv[4], 'utf8').trim())).trim();
166
+ if (!token) throw new Error('the header credential channel sent nothing');
167
+ } else {
168
+ const credentialFile = process.env.${CREDENTIAL_FILE_VAR};
169
+ if (!credentialFile) throw new Error('missing ${CREDENTIAL_FILE_VAR}');
170
+ token = readFileSync(credentialFile, 'utf8').trim();
171
+ if (!token) throw new Error('empty ${CREDENTIAL_FILE_VAR}');
172
+ }
149
173
  const templates = JSON.parse(readFileSync(process.argv[2], 'utf8'));
150
174
  const headers = Object.fromEntries(
151
175
  Object.entries(templates).map(([name, parts]) => [name, parts.join(token)]),
@@ -1100,10 +1124,86 @@ const writePrivateFile = async (path, contents) => {
1100
1124
  await chmod(path, 0o600);
1101
1125
  };
1102
1126
 
1127
+ // F461. The longest socket path the platform takes (sun_path: 104 bytes on
1128
+ // macOS with its terminator; Linux allows 108).
1129
+ const MAX_SOCKET_PATH = 103;
1130
+
1131
+ // F461. A public seat's header helper asks this process for the token over a
1132
+ // Unix socket in the spawn's own folder (0700, the socket 0600), so the
1133
+ // credential file no longer has to outlive the stdio servers' first read. The
1134
+ // token stays in this process's memory.
1135
+ //
1136
+ // The socket answers only a client that first sends this turn's key, a 256-bit
1137
+ // random value in a 0600 file beside it. A Unix connect is not a file read: on
1138
+ // macOS another seat's Seatbelt jail, denied this folder, can still connect to
1139
+ // a socket whose path it learns (measured), because a seat's network is open.
1140
+ // The key keeps the boundary where the file had it, at who can read this
1141
+ // folder. Claude's Read tool cannot open a socket, so reading the key alone
1142
+ // gets it nothing.
1143
+ //
1144
+ // Windows keeps the file: a named pipe's default ACL grants read to Everyone. A
1145
+ // path too long for a socket, or a socket that cannot be set up, keeps the file
1146
+ // too, with a warning.
1147
+ const CHANNEL_IDLE_MS = 10_000;
1148
+ export const startHeaderCredentialChannel = async (dir, token, { platform = process.platform, warn } = {}) => {
1149
+ const value = typeof token === 'string' ? token.trim() : '';
1150
+ if (!value || platform === 'win32') return null;
1151
+ const path = join(dir, 'headers.sock');
1152
+ const keyPath = join(dir, 'headers.key');
1153
+ if (Buffer.byteLength(path) > MAX_SOCKET_PATH) {
1154
+ warn?.(`the header credential socket path is too long (${path}), so this turn keeps its credential file for its HTTP servers`);
1155
+ return null;
1156
+ }
1157
+ const key = randomBytes(32).toString('hex');
1158
+ const expected = Buffer.from(key);
1159
+ const sockets = new Set();
1160
+ const server = createServer((socket) => {
1161
+ sockets.add(socket);
1162
+ socket.on('close', () => sockets.delete(socket));
1163
+ socket.on('error', () => {});
1164
+ socket.setTimeout(CHANNEL_IDLE_MS, () => socket.destroy());
1165
+ socket.setEncoding('utf8');
1166
+ let received = '';
1167
+ socket.on('data', (chunk) => {
1168
+ received += chunk;
1169
+ const newline = received.indexOf('\n');
1170
+ if (newline === -1) {
1171
+ if (received.length > key.length) socket.destroy();
1172
+ return;
1173
+ }
1174
+ const sent = Buffer.from(received.slice(0, newline));
1175
+ socket.removeAllListeners('data');
1176
+ if (sent.length === expected.length && timingSafeEqual(sent, expected)) socket.end(value);
1177
+ else socket.destroy();
1178
+ });
1179
+ });
1180
+ // Ends every open connection too: server.close() alone waits for them.
1181
+ const close = () => new Promise((resolve) => {
1182
+ for (const socket of sockets) socket.destroy();
1183
+ server.close(() => resolve());
1184
+ });
1185
+ try {
1186
+ await writePrivateFile(keyPath, key);
1187
+ await new Promise((resolve, reject) => {
1188
+ server.once('error', reject);
1189
+ server.listen(path, () => { server.off('error', reject); resolve(); });
1190
+ });
1191
+ server.unref();
1192
+ await chmod(path, 0o600);
1193
+ } catch (err) {
1194
+ if (server.listening) await close();
1195
+ await rm(keyPath, { force: true }).catch(() => {});
1196
+ warn?.(`the header credential socket could not be set up (${err?.code || err?.message || err}), so this turn keeps its credential file for its HTTP servers`);
1197
+ return null;
1198
+ }
1199
+ return { path, keyPath, close };
1200
+ };
1201
+
1103
1202
  // Claude's headersHelper is invoked when an HTTP connection is established and
1104
1203
  // again after an authentication retry. Keep the token out of its config and
1105
- // environment: the helper reads the current per-spawn file on every invocation.
1106
- const createTokenHeaderHelpers = async (mcpServers, dir) => {
1204
+ // environment: the helper asks the channel above when there is one, and reads
1205
+ // the current per-spawn file otherwise, on every invocation.
1206
+ const createTokenHeaderHelpers = async (mcpServers, dir, channel = null) => {
1107
1207
  const servers = mcpServers
1108
1208
  .map((server, index) => ({ server, index, templates: getTokenHeaderTemplates(server) }))
1109
1209
  .filter((item) => item.templates);
@@ -1120,6 +1220,7 @@ const createTokenHeaderHelpers = async (mcpServers, dir) => {
1120
1220
  QUOTE_SHELL_ARGUMENT(process.execPath),
1121
1221
  QUOTE_SHELL_ARGUMENT(scriptPath),
1122
1222
  QUOTE_SHELL_ARGUMENT(templatesPath),
1223
+ ...(channel ? [QUOTE_SHELL_ARGUMENT(channel.path), QUOTE_SHELL_ARGUMENT(channel.keyPath)] : []),
1123
1224
  ].join(' '),
1124
1225
  headerNames: Object.keys(templates),
1125
1226
  });
@@ -1194,6 +1295,7 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1194
1295
  const dir = await mkdtemp(join(tmpdir(), 'commonly-claude-mcp-'));
1195
1296
  const file = join(dir, 'mcp-config.json');
1196
1297
  let credential = null;
1298
+ let headerChannel = null;
1197
1299
  try {
1198
1300
  await chmod(dir, 0o700);
1199
1301
  // Written BEFORE the config, because the config may only reference it. It
@@ -1201,8 +1303,19 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1201
1303
  // config — no second lifecycle to get wrong — and so it is inside the one
1202
1304
  // non-workspace path the Seatbelt profile admits.
1203
1305
  credential = writeCredentialFile(ctx.runtimeToken, { agentName: ctx.agentName || 'agent', root: dir });
1306
+ // F461: only a seat that will release its credential (a public one, which
1307
+ // names a ready-file folder) needs the token from somewhere else.
1308
+ const wantsChannel = Boolean(credential?.path && ctx.readyFileDir)
1309
+ && mcpServers.some((server) => getTokenHeaderTemplates(server));
1310
+ if (wantsChannel) {
1311
+ headerChannel = await startHeaderCredentialChannel(dir, ctx.runtimeToken, {
1312
+ platform: ctx.platform,
1313
+ // eslint-disable-next-line no-console
1314
+ warn: (text) => console.warn(`[claude] ${text}`),
1315
+ });
1316
+ }
1204
1317
  const dynamicHeaderHelpers = credential?.path
1205
- ? await createTokenHeaderHelpers(mcpServers, dir)
1318
+ ? await createTokenHeaderHelpers(mcpServers, dir, headerChannel)
1206
1319
  : new Map();
1207
1320
  const unavailableMcp = [];
1208
1321
  const mcpReadDirectories = [];
@@ -1224,7 +1337,7 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1224
1337
  const expansionEnv = buildMcpExpansionEnv(config, {
1225
1338
  ...ctx,
1226
1339
  credentialFile: credential?.path || null,
1227
- headersHelperUsesCredentialFile: dynamicHeaderHelpers.size > 0,
1340
+ headersHelperUsesCredentialFile: dynamicHeaderHelpers.size > 0 && !headerChannel,
1228
1341
  });
1229
1342
  if (expansionEnv[CREDENTIAL_KEY]) {
1230
1343
  // eslint-disable-next-line no-console
@@ -1236,12 +1349,13 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1236
1349
  );
1237
1350
  }
1238
1351
  return {
1239
- dir, file, credential, expansionEnv, unavailableMcp, mcpReadDirectories,
1240
- // A headersHelper reads the credential on every HTTP (re)connect, so a
1241
- // turn that has one keeps the file (F460's named residual).
1242
- headerHelpers: dynamicHeaderHelpers.size,
1352
+ dir, file, credential, expansionEnv, unavailableMcp, mcpReadDirectories, headerChannel,
1353
+ // A headersHelper that reads the file on every HTTP (re)connect keeps it
1354
+ // for the turn. One on the channel (F461) does not.
1355
+ helpersReadCredentialFile: dynamicHeaderHelpers.size > 0 && !headerChannel,
1243
1356
  };
1244
1357
  } catch (err) {
1358
+ try { await headerChannel?.close(); } catch { /* ignore */ }
1245
1359
  try { await rm(dir, { recursive: true, force: true }); } catch { /* ignore */ }
1246
1360
  throw err;
1247
1361
  }
@@ -1744,7 +1858,7 @@ export default {
1744
1858
  return claudeChild;
1745
1859
  };
1746
1860
  const armRelease = () => {
1747
- if (!readyFileDir || !mcpConfig?.credential || mcpConfig.headerHelpers > 0) return;
1861
+ if (!readyFileDir || !mcpConfig?.credential || mcpConfig.helpersReadCredentialFile) return;
1748
1862
  credentialRelease = armCredentialRelease(mcpConfig.credential, {
1749
1863
  readyFiles: readyFiles.map(({ path }) => path),
1750
1864
  label: 'public Claude seat',
@@ -1907,6 +2021,7 @@ export default {
1907
2021
  instanceUrl: ctx.instanceUrl,
1908
2022
  agentName: ctx.agentName,
1909
2023
  publicSeat: publicTrust,
2024
+ platform: ctx._platform || process.platform,
1910
2025
  commandResolution: { env: withClaudePath(ctx.env), ...ctx._commandResolution },
1911
2026
  });
1912
2027
  }
@@ -2076,6 +2191,7 @@ export default {
2076
2191
  credentialRelease?.stop();
2077
2192
  await Promise.all(readyFiles.map(({ path }) => rm(path, { force: true }).catch(() => {})));
2078
2193
  if (ownReadyDir) await rm(ownReadyDir, { recursive: true, force: true }).catch(() => {});
2194
+ try { await mcpConfig?.headerChannel?.close(); } catch { /* ignore */ }
2079
2195
  if (mcpConfig?.dir) {
2080
2196
  try { await rm(mcpConfig.dir, { recursive: true, force: true }); } catch { /* ignore */ }
2081
2197
  }
@@ -288,6 +288,13 @@ const secretMatcher = (secretRoots) => {
288
288
  * target is not proof of no route: the seat's data home gets files during the
289
289
  * turn. Throws ELOOP past MAX_LINK_HOPS, and any lstat or readlink error other
290
290
  * than a missing component.
291
+ *
292
+ * A `..` after the missing component is folded as text (F462). The kernel
293
+ * can't follow such a link at all today. The fold is where it lands once the
294
+ * missing piece exists as a directory, which is all a public seat's tools can
295
+ * create (they have no shell, so no symlink). Only someone with access to the
296
+ * host could make it a link instead, and that person can read the credential
297
+ * directly.
291
298
  */
292
299
  const linkLanding = (path) => {
293
300
  let special = false;
@@ -367,6 +374,15 @@ const linkLanding = (path) => {
367
374
  * public seat, since OpenCode's tools reach the whole worktree. A link to a
368
375
  * regular file outside `boundary` and every secret folder passes: a file holds
369
376
  * no further link.
377
+ *
378
+ * Hard links are not looked for (F462). A readdir gives no inode, so finding
379
+ * them means a stat per file in the worktree, and only the host's owner can
380
+ * make one: a public seat's tools have no shell. The runtime token and the
381
+ * proxy token are new files in a new temp folder each spawn, so no link made
382
+ * before the spawn names them, and a public seat's data home never gets the
383
+ * operator's login. The one lasting secret is the operator's provider.keyFile:
384
+ * a hard link to it in the worktree would pass the jail-path check, but making
385
+ * one is the owner putting their own key in the workspace, the same as a copy.
370
386
  */
371
387
  const scanWorkspaceLinks = (workspace, spawnRoot, {
372
388
  boundary = workspace,