@commonlyai/cli 0.1.398 → 0.1.399

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.
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Host-side file operations under a microVM seat HOME (microsandbox.js).
3
+ *
4
+ * The seat HOME is mounted writable into the guest, and kept on the host
5
+ * between turns. So anything in it may be what a previous turn left: a
6
+ * symbolic link or a Windows junction in place of a folder or a file, pointing
7
+ * anywhere on this computer. Every host write, removal, folder creation and
8
+ * read below the HOME goes through here, and none of them follows a link:
9
+ *
10
+ * - each path component from the HOME down is lstat'ed and must be a real
11
+ * folder (or file); a link is refused, never followed, never removed;
12
+ * - missing folders are made one level at a time, under a parent just checked;
13
+ * - a file is written to a staged name drawn at random and created
14
+ * exclusively (O_CREAT|O_EXCL, plus O_NOFOLLOW where the platform has it),
15
+ * then renamed over the target, which replaces the entry itself;
16
+ * - a read opens with O_NOFOLLOW where the platform has it, checks the handle
17
+ * is a file, and reads at most a cap.
18
+ *
19
+ * Node's lstat reports a Windows junction as a symbolic link, so the same check
20
+ * covers both. A refusal names the path; the person removes the link (not what
21
+ * it points to) and the turn runs again. `io` is a test seam.
22
+ *
23
+ * These run while no VM of the seat runs: before the turn boots, and after msb
24
+ * has exited. That is what makes check-then-act sound here.
25
+ */
26
+ import { randomBytes } from 'crypto';
27
+ import { constants } from 'fs';
28
+ import {
29
+ lstat, mkdir, open, readdir, rename, rmdir, unlink,
30
+ } from 'fs/promises';
31
+ import { basename, join } from 'path';
32
+
33
+ const NOFOLLOW = constants.O_NOFOLLOW || 0;
34
+ const DIRECTORY = constants.O_DIRECTORY || 0;
35
+
36
+ const defaultIo = {
37
+ lstat, mkdir, open, readdir, rename, rmdir, unlink,
38
+ };
39
+
40
+ export const GUEST_PATH_REFUSED = 'guest_path_refused';
41
+
42
+ const refuse = (path, what) => Object.assign(new Error(
43
+ `refusing to touch ${path} in the microVM seat home: it should be ${what} and is a link or something else. `
44
+ + 'A turn can write its seat home; remove that entry (the link itself, not what it points to) and run the turn again.',
45
+ ), { code: GUEST_PATH_REFUSED });
46
+
47
+ const lstatOrNull = async (io, path) => {
48
+ try {
49
+ return await io.lstat(path);
50
+ } catch (err) {
51
+ if (err?.code === 'ENOENT') return null;
52
+ throw err;
53
+ }
54
+ };
55
+
56
+ const plainName = (name) => {
57
+ if (typeof name !== 'string' || !name || name === '.' || name === '..' || basename(name) !== name || /[\\/]/.test(name)) {
58
+ throw new Error(`not a plain name under the microVM seat home: ${JSON.stringify(name)}`);
59
+ }
60
+ return name;
61
+ };
62
+
63
+ /**
64
+ * `root`, then each of `parts` under it, as real folders (made 0700 when
65
+ * missing). The parent of `root` must exist and is not the guest's. Returns
66
+ * the deepest folder's path.
67
+ */
68
+ export const ensureGuestDir = async (root, parts = [], { io = defaultIo } = {}) => {
69
+ let current = root;
70
+ for (const part of [null, ...parts]) {
71
+ if (part !== null) current = join(current, plainName(part));
72
+ // eslint-disable-next-line no-await-in-loop
73
+ let info = await lstatOrNull(io, current);
74
+ if (!info) {
75
+ // eslint-disable-next-line no-await-in-loop
76
+ await io.mkdir(current, { mode: 0o700 });
77
+ // eslint-disable-next-line no-await-in-loop
78
+ info = await io.lstat(current);
79
+ }
80
+ if (info.isSymbolicLink() || !info.isDirectory()) throw refuse(current, 'a folder');
81
+ }
82
+ if (NOFOLLOW && DIRECTORY) {
83
+ let handle;
84
+ try {
85
+ handle = await io.open(current, constants.O_RDONLY | NOFOLLOW | DIRECTORY);
86
+ } catch (err) {
87
+ if (['ELOOP', 'ENOTDIR', 'ENOENT'].includes(err?.code)) throw refuse(current, 'a folder');
88
+ throw err;
89
+ }
90
+ await handle.close();
91
+ }
92
+ return current;
93
+ };
94
+
95
+ // Removes a real folder's contents and the folder, refusing any link inside.
96
+ const removeTree = async (io, path) => {
97
+ for (const name of await io.readdir(path)) {
98
+ const child = join(path, name);
99
+ // eslint-disable-next-line no-await-in-loop
100
+ const info = await io.lstat(child);
101
+ if (info.isSymbolicLink()) throw refuse(child, 'a file or folder');
102
+ // eslint-disable-next-line no-await-in-loop
103
+ if (info.isDirectory()) await removeTree(io, child);
104
+ // eslint-disable-next-line no-await-in-loop
105
+ else await io.unlink(child);
106
+ }
107
+ await io.rmdir(path);
108
+ };
109
+
110
+ /** Removes `dir/name` (a file, or a folder and all it holds). A link anywhere is refused. */
111
+ export const removeGuestEntry = async (dir, name, { io = defaultIo } = {}) => {
112
+ const path = join(dir, plainName(name));
113
+ const info = await lstatOrNull(io, path);
114
+ if (!info) return false;
115
+ if (info.isSymbolicLink()) throw refuse(path, 'a file or folder');
116
+ if (info.isDirectory()) await removeTree(io, path);
117
+ else await io.unlink(path);
118
+ return true;
119
+ };
120
+
121
+ /** Writes `dir/name` through a random, exclusively created staged file. */
122
+ export const writeGuestFile = async (dir, name, text, { io = defaultIo } = {}) => {
123
+ const target = join(dir, plainName(name));
124
+ const existing = await lstatOrNull(io, target);
125
+ if (existing && (existing.isSymbolicLink() || !existing.isFile())) throw refuse(target, 'a file');
126
+ const staged = join(dir, `.${name}.${randomBytes(12).toString('hex')}.tmp`);
127
+ const handle = await io.open(staged, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o600);
128
+ // One cleanup scope from the exclusive open on: a failed write, close or
129
+ // rename removes the staged file and rethrows; only the rename replaces the target.
130
+ let closed = false;
131
+ try {
132
+ await handle.writeFile(text, 'utf8');
133
+ closed = true;
134
+ await handle.close();
135
+ await io.rename(staged, target);
136
+ } catch (err) {
137
+ if (!closed) await handle.close().catch(() => {});
138
+ await io.unlink(staged).catch(() => {});
139
+ throw err;
140
+ }
141
+ };
142
+
143
+ /**
144
+ * Reads `dir/name` as text, at most `maxBytes` of it. Missing reads as null.
145
+ * Returns { text, truncated }.
146
+ */
147
+ export const readGuestFile = async (dir, name, { maxBytes, io = defaultIo } = {}) => {
148
+ const path = join(dir, plainName(name));
149
+ const info = await lstatOrNull(io, path);
150
+ if (!info) return null;
151
+ if (info.isSymbolicLink() || !info.isFile()) throw refuse(path, 'a file');
152
+ let handle;
153
+ try {
154
+ handle = await io.open(path, constants.O_RDONLY | NOFOLLOW);
155
+ } catch (err) {
156
+ if (err?.code === 'ELOOP') throw refuse(path, 'a file');
157
+ throw err;
158
+ }
159
+ try {
160
+ if (!(await handle.stat()).isFile()) throw refuse(path, 'a file');
161
+ const buffer = Buffer.alloc(maxBytes + 1);
162
+ let filled = 0;
163
+ while (filled < buffer.length) {
164
+ // eslint-disable-next-line no-await-in-loop
165
+ const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);
166
+ if (!bytesRead) break;
167
+ filled += bytesRead;
168
+ }
169
+ const truncated = filled > maxBytes;
170
+ return { text: buffer.subarray(0, Math.min(filled, maxBytes)).toString('utf8'), truncated };
171
+ } finally {
172
+ await handle.close();
173
+ }
174
+ };
175
+
176
+ export default {
177
+ ensureGuestDir, readGuestFile, removeGuestEntry, writeGuestFile,
178
+ };
@@ -11,14 +11,16 @@
11
11
  * Only the adapters that run inside these mechanisms are checked. Codex
12
12
  * confines with its own permission profiles (mode.js), except on native
13
13
  * Windows: there a public Codex seat is refused, and any other runs only by the
14
- * person's own opt-in (CODEX_WINDOWS_MESSAGE below). pi confines an
14
+ * person's own opt-in (CODEX_WINDOWS_MESSAGE below). With the microVM opt-in
15
+ * (COMMONLY_SANDBOX_MICROVM=1) a public Codex seat runs in the microVM instead,
16
+ * and only where WHP is on. pi confines an
15
17
  * explicitly public seat with Seatbelt and refuses one it cannot confine at
16
18
  * attach (validateEnvironment) and at spawn (adapters/pi.js); a Connect-page pi
17
19
  * seat declares no sandbox and is not checked here.
18
20
  */
19
21
 
20
22
  import { normalizeSandboxTrust } from '../environment.js';
21
- import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from './mode.js';
23
+ import { PUBLIC_SANDBOX_MODES, resolveCodexSandboxMode, resolvePublicSandboxMode } from './mode.js';
22
24
  import { detectBwrap as defaultDetectBwrap, detectBwrapLoopback as defaultDetectBwrapLoopback } from './bwrap.js';
23
25
  import { detectSeatbelt as defaultDetectSeatbelt } from './seatbelt.js';
24
26
  import { codexTrustedPerimeter } from './codex-perimeter.js';
@@ -258,6 +260,19 @@ export const hostSandboxRefusal = ({
258
260
  }
259
261
  if (platform !== 'win32') return null;
260
262
  if (trust === 'workspace') return null;
263
+ // Native Windows, opt-in: a public Codex seat runs inside the microVM
264
+ // (mode.js resolveCodexSandboxMode), and only where WHP is on. Never
265
+ // Codex's own Windows sandbox, which can't enforce the public profile.
266
+ if (trust === 'public' && resolveCodexSandboxMode(normalizeSandboxTrust(environment?.sandbox), platform, env) === 'microvm') {
267
+ try {
268
+ checkMicrovmAttach({
269
+ adapterName, platform, env, probe: detectWhp,
270
+ });
271
+ } catch (error) {
272
+ return error.message;
273
+ }
274
+ return null;
275
+ }
261
276
  if (trust === 'public') return optedIn === true ? CODEX_WINDOWS_PUBLIC_MESSAGE : CODEX_WINDOWS_MESSAGE;
262
277
  // No public trust: `agent run` removed the block for this run after
263
278
  // confirming every pod private, or the seat never had one. Either way it