@jini-ai/sandbox 0.4.1 → 0.4.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @jini-ai/sandbox
2
2
 
3
+ ## 0.4.3 — 2026-10-22
4
+
5
+ - 2026-10-22: Security queue fixes for the e2b provider, coverage.
6
+
3
7
  ## 0.4.1
4
8
 
5
9
  ### Patch Changes
@@ -24,6 +24,13 @@ const wrap_e2b_sandbox_js_1 = require("./wrap-e2b-sandbox.js");
24
24
  const DEFAULT_PROJECT_ROOT = '/home/user/app';
25
25
  const DEFAULT_PREVIEW_PORT = 5173;
26
26
  const DEFAULT_PREVIEW_CHECK_TIMEOUT_MS = 3_000;
27
+ function resolveSessionConfig({ config }, _options = {}) {
28
+ return {
29
+ projectRoot: config.projectRoot ?? DEFAULT_PROJECT_ROOT,
30
+ previewPort: config.previewPort ?? DEFAULT_PREVIEW_PORT,
31
+ previewCheckTimeoutMs: config.previewCheckTimeoutMs ?? DEFAULT_PREVIEW_CHECK_TIMEOUT_MS,
32
+ };
33
+ }
27
34
  /**
28
35
  * Adapts a real `Sandbox` into the object-argument `E2bSandboxHandle` port.
29
36
  * SDK positional arguments are translated only at this boundary. `files` is wrapped with one explicit function per member instead, because
@@ -81,11 +88,7 @@ function createE2bSandboxProvider(_requiredArgs, config = {}) {
81
88
  catch (error) {
82
89
  throw new errors_js_1.SandboxOperationError({ category: (0, categorize_e2b_error_js_1.categorizeE2bError)({ error }), message: 'Failed to create the sandbox' }, { cause: error });
83
90
  }
84
- return (0, wrap_e2b_sandbox_js_1.wrapE2bSandbox)({ handle: toE2bHandle({ sandbox }), config: {
85
- projectRoot: config.projectRoot ?? DEFAULT_PROJECT_ROOT,
86
- previewPort: config.previewPort ?? DEFAULT_PREVIEW_PORT,
87
- previewCheckTimeoutMs: config.previewCheckTimeoutMs ?? DEFAULT_PREVIEW_CHECK_TIMEOUT_MS,
88
- } }, config.fetchImpl === undefined ? {} : { fetchImpl: config.fetchImpl });
91
+ return (0, wrap_e2b_sandbox_js_1.wrapE2bSandbox)({ handle: toE2bHandle({ sandbox }), config: resolveSessionConfig({ config }) }, config.fetchImpl === undefined ? {} : { fetchImpl: config.fetchImpl });
89
92
  },
90
93
  };
91
94
  }
@@ -54,11 +54,6 @@ function buildCommand(command, args) {
54
54
  function toCommandResult(result) {
55
55
  return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
56
56
  }
57
- /** Converts `SandboxFile.content` into what E2B's `files.write` actually accepts (`string |
58
- * ArrayBuffer`, no `Uint8Array` overload). */
59
- function toE2bWriteData(content) {
60
- return typeof content === 'string' ? content : (0, to_array_buffer_js_1.toArrayBuffer)({ bytes: content });
61
- }
62
57
  /**
63
58
  * The `onStdout`/`onStderr` fragment to spread into an E2B `commands.run` call — present only
64
59
  * when `options.onOutput` is given. Built with a conditional spread rather than
@@ -115,6 +110,23 @@ function relativeToRoot(absolutePath, projectRoot) {
115
110
  function isExcludedPath(relativePath) {
116
111
  return relativePath.split('/').some((segment) => EXCLUDED_DIR_NAMES.has(segment));
117
112
  }
113
+ /** Resolves a caller's project-relative path; rejects escaped or malformed paths before I/O.
114
+ * @complexity O(n) time/space in path length. */
115
+ function resolveProjectPath({ projectRoot, path }, _options = {}) {
116
+ const resolved = node_path_1.posix.resolve(projectRoot, path);
117
+ const relative = node_path_1.posix.relative(projectRoot, resolved);
118
+ if (path.includes('\0') || node_path_1.posix.isAbsolute(path) || relative === '..' || relative.startsWith('../')) {
119
+ throw new errors_js_1.SandboxOperationError({ category: 'permission-denied', message: 'Sandbox path must stay inside the project root' });
120
+ }
121
+ return resolved;
122
+ }
123
+ function rollbackMount({ mounted, mountedFiles }, _options = {}) {
124
+ for (const [path, entry] of mounted) {
125
+ // Identity preserves a newer overlapping mount even when its content is identical.
126
+ if (mountedFiles.get(path) === entry)
127
+ mountedFiles.delete(path);
128
+ }
129
+ }
118
130
  async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } = {}) {
119
131
  const { projectRoot, previewPort, previewCheckTimeoutMs } = config;
120
132
  try {
@@ -178,7 +190,7 @@ async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } = {}) {
178
190
  return;
179
191
  const mounted = new Map();
180
192
  for (const file of files) {
181
- const path = relativeToRoot(node_path_1.posix.join(projectRoot, file.path), projectRoot);
193
+ const path = relativeToRoot(resolveProjectPath({ projectRoot, path: file.path }), projectRoot);
182
194
  mounted.set(path, { fingerprint: fingerprint(file.content) });
183
195
  }
184
196
  for (const [path, entry] of mounted) {
@@ -186,16 +198,19 @@ async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } = {}) {
186
198
  mountingPaths.set(path, (mountingPaths.get(path) ?? 0) + 1);
187
199
  }
188
200
  try {
189
- await handle.files.write({ files: files.map((file) => ({
190
- path: node_path_1.posix.join(projectRoot, file.path),
191
- data: toE2bWriteData(file.content),
192
- })) });
201
+ await handle.files.write({ files: files.map((file) => {
202
+ const path = resolveProjectPath({ projectRoot, path: file.path });
203
+ const content = file.content;
204
+ return {
205
+ path,
206
+ /** Converts `SandboxFile.content` into what E2B's `files.write` actually accepts (`string |
207
+ * ArrayBuffer`, no `Uint8Array` overload). */
208
+ data: typeof content === 'string' ? content : (0, to_array_buffer_js_1.toArrayBuffer)({ bytes: content }),
209
+ };
210
+ }) });
193
211
  }
194
212
  catch (error) {
195
- for (const [path, entry] of mounted) {
196
- if (mountedFiles.get(path) === entry)
197
- mountedFiles.delete(path);
198
- }
213
+ rollbackMount({ mounted, mountedFiles });
199
214
  throw wrapE2bError(error, 'Failed to write files into the sandbox');
200
215
  }
201
216
  finally {
@@ -209,15 +224,16 @@ async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } = {}) {
209
224
  }
210
225
  },
211
226
  async readFile({ path }) {
227
+ const resolved = resolveProjectPath({ projectRoot, path });
212
228
  try {
213
- return await handle.files.read({ path: node_path_1.posix.join(projectRoot, path), format: 'bytes' });
229
+ return await handle.files.read({ path: resolved, format: 'bytes' });
214
230
  }
215
231
  catch (error) {
216
232
  throw wrapE2bError(error, `Failed to read ${path}`);
217
233
  }
218
234
  },
219
235
  async listFiles(_required, { directory } = {}) {
220
- const base = directory ? node_path_1.posix.join(projectRoot, directory) : projectRoot;
236
+ const base = resolveProjectPath({ projectRoot, path: directory ?? '.' });
221
237
  let entries;
222
238
  try {
223
239
  entries = await handle.files.list({ path: base }, { depth: MAX_LIST_DEPTH });
@@ -105,6 +105,8 @@ export interface NodeWorkerFactoryOptions {
105
105
  }
106
106
  /**
107
107
  * Native Node worker factory. TypeScript bootstrap configuration is explicit and host-owned.
108
+ * Worker stdin is disabled and output is drained without forwarding to parent stdio;
109
+ * results and controlled failures travel over the message/error ports instead.
108
110
  * @param required Environment copied to each worker; nothing reads the parent environment.
109
111
  * @param options Optional native creation port and TypeScript registration module; its eval entry suppresses V8 coverage.
110
112
  * @returns WorkerFactory for caller-owned JS/TS entry paths, with no package-relative lookup.
@@ -101,6 +101,8 @@ function renderInWorkerSandbox(required, options = {}) {
101
101
  }
102
102
  /**
103
103
  * Native Node worker factory. TypeScript bootstrap configuration is explicit and host-owned.
104
+ * Worker stdin is disabled and output is drained without forwarding to parent stdio;
105
+ * results and controlled failures travel over the message/error ports instead.
104
106
  * @param required Environment copied to each worker; nothing reads the parent environment.
105
107
  * @param options Optional native creation port and TypeScript registration module; its eval entry suppresses V8 coverage.
106
108
  * @returns WorkerFactory for caller-owned JS/TS entry paths, with no package-relative lookup.
@@ -110,6 +112,10 @@ function createNodeWorkerFactory({ env }, options = {}) {
110
112
  return {
111
113
  spawn({ workerEntry, payload, resourceLimits }) {
112
114
  const workerEnv = { ...env };
115
+ const workerOptions = {
116
+ workerData: payload, resourceLimits, env: workerEnv, execArgv: [],
117
+ stdin: false, stdout: true, stderr: true,
118
+ };
113
119
  let worker;
114
120
  // A CommonJS-typed TS entry bypasses --import loader hooks for its first file and
115
121
  // can fail with "Cannot use import statement outside a module" despite the flag.
@@ -126,13 +132,16 @@ function createNodeWorkerFactory({ env }, options = {}) {
126
132
  // directory is created merely to leave cleanup behind.
127
133
  delete workerEnv.NODE_V8_COVERAGE;
128
134
  const bootstrap = `require(${JSON.stringify(options.typescriptBootstrap.registerModulePath)}).register();\nrequire(${JSON.stringify(workerEntry)});\n`;
129
- const workerOptions = { eval: true, workerData: payload, resourceLimits, env: workerEnv, execArgv: [] };
135
+ workerOptions.eval = true;
130
136
  worker = options.createWorker ? options.createWorker({ entry: bootstrap, options: workerOptions }, {}) : new node_worker_threads_1.Worker(bootstrap, workerOptions);
131
137
  }
132
138
  else {
133
- const workerOptions = { workerData: payload, resourceLimits, env: workerEnv, execArgv: [] };
134
139
  worker = options.createWorker ? options.createWorker({ entry: workerEntry, options: workerOptions }, {}) : new node_worker_threads_1.Worker(workerEntry, workerOptions);
135
140
  }
141
+ // Explicit output streams avoid Node's automatic forwarding to detached parent
142
+ // streams. Drain them so worker logging cannot block a render or grow a buffer.
143
+ worker.stdout.resume();
144
+ worker.stderr.resume();
136
145
  return {
137
146
  once(input) {
138
147
  if (input.event === "message")
@@ -20,6 +20,13 @@ import { wrapE2bSandbox } from './wrap-e2b-sandbox.js';
20
20
  const DEFAULT_PROJECT_ROOT = '/home/user/app';
21
21
  const DEFAULT_PREVIEW_PORT = 5173;
22
22
  const DEFAULT_PREVIEW_CHECK_TIMEOUT_MS = 3_000;
23
+ function resolveSessionConfig({ config }, _options = {}) {
24
+ return {
25
+ projectRoot: config.projectRoot ?? DEFAULT_PROJECT_ROOT,
26
+ previewPort: config.previewPort ?? DEFAULT_PREVIEW_PORT,
27
+ previewCheckTimeoutMs: config.previewCheckTimeoutMs ?? DEFAULT_PREVIEW_CHECK_TIMEOUT_MS,
28
+ };
29
+ }
23
30
  /**
24
31
  * Adapts a real `Sandbox` into the object-argument `E2bSandboxHandle` port.
25
32
  * SDK positional arguments are translated only at this boundary. `files` is wrapped with one explicit function per member instead, because
@@ -77,11 +84,7 @@ export function createE2bSandboxProvider(_requiredArgs, config = {}) {
77
84
  catch (error) {
78
85
  throw new SandboxOperationError({ category: categorizeE2bError({ error }), message: 'Failed to create the sandbox' }, { cause: error });
79
86
  }
80
- return wrapE2bSandbox({ handle: toE2bHandle({ sandbox }), config: {
81
- projectRoot: config.projectRoot ?? DEFAULT_PROJECT_ROOT,
82
- previewPort: config.previewPort ?? DEFAULT_PREVIEW_PORT,
83
- previewCheckTimeoutMs: config.previewCheckTimeoutMs ?? DEFAULT_PREVIEW_CHECK_TIMEOUT_MS,
84
- } }, config.fetchImpl === undefined ? {} : { fetchImpl: config.fetchImpl });
87
+ return wrapE2bSandbox({ handle: toE2bHandle({ sandbox }), config: resolveSessionConfig({ config }) }, config.fetchImpl === undefined ? {} : { fetchImpl: config.fetchImpl });
85
88
  },
86
89
  };
87
90
  }
@@ -50,11 +50,6 @@ function buildCommand(command, args) {
50
50
  function toCommandResult(result) {
51
51
  return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
52
52
  }
53
- /** Converts `SandboxFile.content` into what E2B's `files.write` actually accepts (`string |
54
- * ArrayBuffer`, no `Uint8Array` overload). */
55
- function toE2bWriteData(content) {
56
- return typeof content === 'string' ? content : toArrayBuffer({ bytes: content });
57
- }
58
53
  /**
59
54
  * The `onStdout`/`onStderr` fragment to spread into an E2B `commands.run` call — present only
60
55
  * when `options.onOutput` is given. Built with a conditional spread rather than
@@ -111,6 +106,23 @@ function relativeToRoot(absolutePath, projectRoot) {
111
106
  function isExcludedPath(relativePath) {
112
107
  return relativePath.split('/').some((segment) => EXCLUDED_DIR_NAMES.has(segment));
113
108
  }
109
+ /** Resolves a caller's project-relative path; rejects escaped or malformed paths before I/O.
110
+ * @complexity O(n) time/space in path length. */
111
+ function resolveProjectPath({ projectRoot, path }, _options = {}) {
112
+ const resolved = posix.resolve(projectRoot, path);
113
+ const relative = posix.relative(projectRoot, resolved);
114
+ if (path.includes('\0') || posix.isAbsolute(path) || relative === '..' || relative.startsWith('../')) {
115
+ throw new SandboxOperationError({ category: 'permission-denied', message: 'Sandbox path must stay inside the project root' });
116
+ }
117
+ return resolved;
118
+ }
119
+ function rollbackMount({ mounted, mountedFiles }, _options = {}) {
120
+ for (const [path, entry] of mounted) {
121
+ // Identity preserves a newer overlapping mount even when its content is identical.
122
+ if (mountedFiles.get(path) === entry)
123
+ mountedFiles.delete(path);
124
+ }
125
+ }
114
126
  export async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } = {}) {
115
127
  const { projectRoot, previewPort, previewCheckTimeoutMs } = config;
116
128
  try {
@@ -174,7 +186,7 @@ export async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } =
174
186
  return;
175
187
  const mounted = new Map();
176
188
  for (const file of files) {
177
- const path = relativeToRoot(posix.join(projectRoot, file.path), projectRoot);
189
+ const path = relativeToRoot(resolveProjectPath({ projectRoot, path: file.path }), projectRoot);
178
190
  mounted.set(path, { fingerprint: fingerprint(file.content) });
179
191
  }
180
192
  for (const [path, entry] of mounted) {
@@ -182,16 +194,19 @@ export async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } =
182
194
  mountingPaths.set(path, (mountingPaths.get(path) ?? 0) + 1);
183
195
  }
184
196
  try {
185
- await handle.files.write({ files: files.map((file) => ({
186
- path: posix.join(projectRoot, file.path),
187
- data: toE2bWriteData(file.content),
188
- })) });
197
+ await handle.files.write({ files: files.map((file) => {
198
+ const path = resolveProjectPath({ projectRoot, path: file.path });
199
+ const content = file.content;
200
+ return {
201
+ path,
202
+ /** Converts `SandboxFile.content` into what E2B's `files.write` actually accepts (`string |
203
+ * ArrayBuffer`, no `Uint8Array` overload). */
204
+ data: typeof content === 'string' ? content : toArrayBuffer({ bytes: content }),
205
+ };
206
+ }) });
189
207
  }
190
208
  catch (error) {
191
- for (const [path, entry] of mounted) {
192
- if (mountedFiles.get(path) === entry)
193
- mountedFiles.delete(path);
194
- }
209
+ rollbackMount({ mounted, mountedFiles });
195
210
  throw wrapE2bError(error, 'Failed to write files into the sandbox');
196
211
  }
197
212
  finally {
@@ -205,15 +220,16 @@ export async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } =
205
220
  }
206
221
  },
207
222
  async readFile({ path }) {
223
+ const resolved = resolveProjectPath({ projectRoot, path });
208
224
  try {
209
- return await handle.files.read({ path: posix.join(projectRoot, path), format: 'bytes' });
225
+ return await handle.files.read({ path: resolved, format: 'bytes' });
210
226
  }
211
227
  catch (error) {
212
228
  throw wrapE2bError(error, `Failed to read ${path}`);
213
229
  }
214
230
  },
215
231
  async listFiles(_required, { directory } = {}) {
216
- const base = directory ? posix.join(projectRoot, directory) : projectRoot;
232
+ const base = resolveProjectPath({ projectRoot, path: directory ?? '.' });
217
233
  let entries;
218
234
  try {
219
235
  entries = await handle.files.list({ path: base }, { depth: MAX_LIST_DEPTH });
@@ -105,6 +105,8 @@ export interface NodeWorkerFactoryOptions {
105
105
  }
106
106
  /**
107
107
  * Native Node worker factory. TypeScript bootstrap configuration is explicit and host-owned.
108
+ * Worker stdin is disabled and output is drained without forwarding to parent stdio;
109
+ * results and controlled failures travel over the message/error ports instead.
108
110
  * @param required Environment copied to each worker; nothing reads the parent environment.
109
111
  * @param options Optional native creation port and TypeScript registration module; its eval entry suppresses V8 coverage.
110
112
  * @returns WorkerFactory for caller-owned JS/TS entry paths, with no package-relative lookup.
@@ -94,6 +94,8 @@ export function renderInWorkerSandbox(required, options = {}) {
94
94
  }
95
95
  /**
96
96
  * Native Node worker factory. TypeScript bootstrap configuration is explicit and host-owned.
97
+ * Worker stdin is disabled and output is drained without forwarding to parent stdio;
98
+ * results and controlled failures travel over the message/error ports instead.
97
99
  * @param required Environment copied to each worker; nothing reads the parent environment.
98
100
  * @param options Optional native creation port and TypeScript registration module; its eval entry suppresses V8 coverage.
99
101
  * @returns WorkerFactory for caller-owned JS/TS entry paths, with no package-relative lookup.
@@ -103,6 +105,10 @@ export function createNodeWorkerFactory({ env }, options = {}) {
103
105
  return {
104
106
  spawn({ workerEntry, payload, resourceLimits }) {
105
107
  const workerEnv = { ...env };
108
+ const workerOptions = {
109
+ workerData: payload, resourceLimits, env: workerEnv, execArgv: [],
110
+ stdin: false, stdout: true, stderr: true,
111
+ };
106
112
  let worker;
107
113
  // A CommonJS-typed TS entry bypasses --import loader hooks for its first file and
108
114
  // can fail with "Cannot use import statement outside a module" despite the flag.
@@ -119,13 +125,16 @@ export function createNodeWorkerFactory({ env }, options = {}) {
119
125
  // directory is created merely to leave cleanup behind.
120
126
  delete workerEnv.NODE_V8_COVERAGE;
121
127
  const bootstrap = `require(${JSON.stringify(options.typescriptBootstrap.registerModulePath)}).register();\nrequire(${JSON.stringify(workerEntry)});\n`;
122
- const workerOptions = { eval: true, workerData: payload, resourceLimits, env: workerEnv, execArgv: [] };
128
+ workerOptions.eval = true;
123
129
  worker = options.createWorker ? options.createWorker({ entry: bootstrap, options: workerOptions }, {}) : new Worker(bootstrap, workerOptions);
124
130
  }
125
131
  else {
126
- const workerOptions = { workerData: payload, resourceLimits, env: workerEnv, execArgv: [] };
127
132
  worker = options.createWorker ? options.createWorker({ entry: workerEntry, options: workerOptions }, {}) : new Worker(workerEntry, workerOptions);
128
133
  }
134
+ // Explicit output streams avoid Node's automatic forwarding to detached parent
135
+ // streams. Drain them so worker logging cannot block a render or grow a buffer.
136
+ worker.stdout.resume();
137
+ worker.stderr.resume();
129
138
  return {
130
139
  once(input) {
131
140
  if (input.event === "message")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/sandbox",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Execution/sandbox sibling to @jini-ai/vibecoding's edit loop: boot an environment, mount files, install deps, run commands, preview, and tear down — behind one interface with a driver-neutral core. Import `./core` with no adapter installed; add `./e2b` for the E2B (Firecracker microVM) backend.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {