@cloudflare/sandbox 0.0.0-9375c1e → 0.0.0-93c6cc7
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 +162 -15
- package/Dockerfile +172 -86
- package/README.md +92 -769
- package/dist/index.d.ts +1953 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3280 -0
- package/dist/index.js.map +1 -0
- package/package.json +16 -8
- package/src/clients/base-client.ts +295 -0
- package/src/clients/command-client.ts +115 -0
- package/src/clients/file-client.ts +300 -0
- package/src/clients/git-client.ts +98 -0
- package/src/clients/index.ts +64 -0
- package/src/clients/interpreter-client.ts +333 -0
- package/src/clients/port-client.ts +105 -0
- package/src/clients/process-client.ts +180 -0
- package/src/clients/sandbox-client.ts +39 -0
- package/src/clients/types.ts +88 -0
- package/src/clients/utility-client.ts +156 -0
- package/src/errors/adapter.ts +238 -0
- package/src/errors/classes.ts +594 -0
- package/src/errors/index.ts +109 -0
- package/src/file-stream.ts +169 -0
- package/src/index.ts +93 -53
- package/src/interpreter.ts +62 -44
- package/src/request-handler.ts +94 -55
- package/src/sandbox.ts +1013 -492
- package/src/security.ts +34 -28
- package/src/sse-parser.ts +8 -11
- package/src/version.ts +6 -0
- package/startup.sh +3 -0
- package/tests/base-client.test.ts +364 -0
- package/tests/command-client.test.ts +444 -0
- package/tests/file-client.test.ts +831 -0
- package/tests/file-stream.test.ts +310 -0
- package/tests/get-sandbox.test.ts +149 -0
- package/tests/git-client.test.ts +487 -0
- package/tests/port-client.test.ts +293 -0
- package/tests/process-client.test.ts +683 -0
- package/tests/request-handler.test.ts +292 -0
- package/tests/sandbox.test.ts +739 -0
- package/tests/sse-parser.test.ts +291 -0
- package/tests/utility-client.test.ts +339 -0
- package/tests/version.test.ts +16 -0
- package/tests/wrangler.jsonc +35 -0
- package/tsconfig.json +9 -1
- package/tsdown.config.ts +12 -0
- package/vitest.config.ts +31 -0
- package/container_src/bun.lock +0 -122
- package/container_src/circuit-breaker.ts +0 -121
- package/container_src/control-process.ts +0 -784
- package/container_src/handler/exec.ts +0 -185
- package/container_src/handler/file.ts +0 -406
- package/container_src/handler/git.ts +0 -130
- package/container_src/handler/ports.ts +0 -314
- package/container_src/handler/process.ts +0 -568
- package/container_src/handler/session.ts +0 -92
- package/container_src/index.ts +0 -601
- package/container_src/isolation.ts +0 -1038
- package/container_src/jupyter-server.ts +0 -579
- package/container_src/jupyter-service.ts +0 -461
- package/container_src/jupyter_config.py +0 -48
- package/container_src/mime-processor.ts +0 -255
- package/container_src/package.json +0 -18
- package/container_src/shell-escape.ts +0 -42
- package/container_src/startup.sh +0 -84
- package/container_src/types.ts +0 -131
- package/src/client.ts +0 -1009
- package/src/errors.ts +0 -218
- package/src/interpreter-types.ts +0 -383
- package/src/jupyter-client.ts +0 -349
- package/src/types.ts +0 -502
package/src/sandbox.ts
CHANGED
|
@@ -1,79 +1,135 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import type { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { Container, getContainer, switchPort } from '@cloudflare/containers';
|
|
3
3
|
import type {
|
|
4
4
|
CodeContext,
|
|
5
5
|
CreateContextOptions,
|
|
6
|
-
ExecutionResult,
|
|
7
|
-
RunCodeOptions,
|
|
8
|
-
} from "./interpreter-types";
|
|
9
|
-
import { JupyterClient } from "./jupyter-client";
|
|
10
|
-
import { isLocalhostPattern } from "./request-handler";
|
|
11
|
-
import {
|
|
12
|
-
logSecurityEvent,
|
|
13
|
-
SecurityError,
|
|
14
|
-
sanitizeSandboxId,
|
|
15
|
-
validatePort,
|
|
16
|
-
} from "./security";
|
|
17
|
-
import { parseSSEStream } from "./sse-parser";
|
|
18
|
-
import type {
|
|
19
6
|
ExecEvent,
|
|
20
7
|
ExecOptions,
|
|
21
8
|
ExecResult,
|
|
22
|
-
|
|
9
|
+
ExecutionResult,
|
|
23
10
|
ExecutionSession,
|
|
24
11
|
ISandbox,
|
|
25
12
|
Process,
|
|
26
13
|
ProcessOptions,
|
|
27
14
|
ProcessStatus,
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
15
|
+
RunCodeOptions,
|
|
16
|
+
SandboxOptions,
|
|
17
|
+
SessionOptions,
|
|
18
|
+
StreamOptions
|
|
19
|
+
} from '@repo/shared';
|
|
20
|
+
import {
|
|
21
|
+
createLogger,
|
|
22
|
+
runWithLogger,
|
|
23
|
+
type SessionDeleteResult,
|
|
24
|
+
TraceContext
|
|
25
|
+
} from '@repo/shared';
|
|
26
|
+
import { type ExecuteResponse, SandboxClient } from './clients';
|
|
27
|
+
import type { ErrorResponse } from './errors';
|
|
28
|
+
import { CustomDomainRequiredError, ErrorCode } from './errors';
|
|
29
|
+
import { CodeInterpreter } from './interpreter';
|
|
30
|
+
import { isLocalhostPattern } from './request-handler';
|
|
31
|
+
import { SecurityError, sanitizeSandboxId, validatePort } from './security';
|
|
32
|
+
import { parseSSEStream } from './sse-parser';
|
|
33
|
+
import { SDK_VERSION } from './version';
|
|
34
|
+
|
|
35
|
+
export function getSandbox(
|
|
36
|
+
ns: DurableObjectNamespace<Sandbox>,
|
|
37
|
+
id: string,
|
|
38
|
+
options?: SandboxOptions
|
|
39
|
+
): Sandbox {
|
|
40
|
+
const stub = getContainer(ns, id) as unknown as Sandbox;
|
|
34
41
|
|
|
35
42
|
// Store the name on first access
|
|
36
43
|
stub.setSandboxName?.(id);
|
|
37
44
|
|
|
38
|
-
|
|
45
|
+
if (options?.baseUrl) {
|
|
46
|
+
stub.setBaseUrl(options.baseUrl);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (options?.sleepAfter !== undefined) {
|
|
50
|
+
stub.setSleepAfter(options.sleepAfter);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (options?.keepAlive !== undefined) {
|
|
54
|
+
stub.setKeepAlive(options.keepAlive);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return Object.assign(stub, {
|
|
58
|
+
wsConnect: connect(stub)
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function connect(stub: {
|
|
63
|
+
fetch: (request: Request) => Promise<Response>;
|
|
64
|
+
}) {
|
|
65
|
+
return async (request: Request, port: number) => {
|
|
66
|
+
// Validate port before routing
|
|
67
|
+
if (!validatePort(port)) {
|
|
68
|
+
throw new SecurityError(
|
|
69
|
+
`Invalid or restricted port: ${port}. Ports must be in range 1024-65535 and not reserved.`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
const portSwitchedRequest = switchPort(request, port);
|
|
73
|
+
return await stub.fetch(portSwitchedRequest);
|
|
74
|
+
};
|
|
39
75
|
}
|
|
40
76
|
|
|
41
77
|
export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
|
|
42
78
|
defaultPort = 3000; // Default port for the container's Bun server
|
|
43
|
-
sleepAfter =
|
|
44
|
-
client: JupyterClient;
|
|
45
|
-
private sandboxName: string | null = null;
|
|
46
|
-
private codeInterpreter: CodeInterpreter;
|
|
47
|
-
private defaultSession: ExecutionSession | null = null;
|
|
79
|
+
sleepAfter: string | number = '10m'; // Sleep the sandbox if no requests are made in this timeframe
|
|
48
80
|
|
|
49
|
-
|
|
81
|
+
client: SandboxClient;
|
|
82
|
+
private codeInterpreter: CodeInterpreter;
|
|
83
|
+
private sandboxName: string | null = null;
|
|
84
|
+
private baseUrl: string | null = null;
|
|
85
|
+
private portTokens: Map<number, string> = new Map();
|
|
86
|
+
private defaultSession: string | null = null;
|
|
87
|
+
envVars: Record<string, string> = {};
|
|
88
|
+
private logger: ReturnType<typeof createLogger>;
|
|
89
|
+
private keepAliveEnabled: boolean = false;
|
|
90
|
+
|
|
91
|
+
constructor(ctx: DurableObjectState<{}>, env: Env) {
|
|
50
92
|
super(ctx, env);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
93
|
+
|
|
94
|
+
const envObj = env as any;
|
|
95
|
+
// Set sandbox environment variables from env object
|
|
96
|
+
const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;
|
|
97
|
+
sandboxEnvKeys.forEach((key) => {
|
|
98
|
+
if (envObj?.[key]) {
|
|
99
|
+
this.envVars[key] = envObj[key];
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
this.logger = createLogger({
|
|
104
|
+
component: 'sandbox-do',
|
|
105
|
+
sandboxId: this.ctx.id.toString()
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
this.client = new SandboxClient({
|
|
109
|
+
logger: this.logger,
|
|
66
110
|
port: 3000, // Control plane port
|
|
67
|
-
stub: this
|
|
111
|
+
stub: this
|
|
68
112
|
});
|
|
69
113
|
|
|
70
|
-
// Initialize code interpreter
|
|
114
|
+
// Initialize code interpreter - pass 'this' after client is ready
|
|
115
|
+
// The CodeInterpreter extracts client.interpreter from the sandbox
|
|
71
116
|
this.codeInterpreter = new CodeInterpreter(this);
|
|
72
117
|
|
|
73
|
-
// Load the sandbox name from storage on initialization
|
|
118
|
+
// Load the sandbox name, port tokens, and default session from storage on initialization
|
|
74
119
|
this.ctx.blockConcurrencyWhile(async () => {
|
|
75
120
|
this.sandboxName =
|
|
76
|
-
(await this.ctx.storage.get<string>(
|
|
121
|
+
(await this.ctx.storage.get<string>('sandboxName')) || null;
|
|
122
|
+
this.defaultSession =
|
|
123
|
+
(await this.ctx.storage.get<string>('defaultSession')) || null;
|
|
124
|
+
const storedTokens =
|
|
125
|
+
(await this.ctx.storage.get<Record<string, string>>('portTokens')) ||
|
|
126
|
+
{};
|
|
127
|
+
|
|
128
|
+
// Convert stored tokens back to Map
|
|
129
|
+
this.portTokens = new Map();
|
|
130
|
+
for (const [portStr, token] of Object.entries(storedTokens)) {
|
|
131
|
+
this.portTokens.set(parseInt(portStr, 10), token);
|
|
132
|
+
}
|
|
77
133
|
});
|
|
78
134
|
}
|
|
79
135
|
|
|
@@ -81,62 +137,227 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
|
|
|
81
137
|
async setSandboxName(name: string): Promise<void> {
|
|
82
138
|
if (!this.sandboxName) {
|
|
83
139
|
this.sandboxName = name;
|
|
84
|
-
await this.ctx.storage.put(
|
|
85
|
-
|
|
140
|
+
await this.ctx.storage.put('sandboxName', name);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// RPC method to set the base URL
|
|
145
|
+
async setBaseUrl(baseUrl: string): Promise<void> {
|
|
146
|
+
if (!this.baseUrl) {
|
|
147
|
+
this.baseUrl = baseUrl;
|
|
148
|
+
await this.ctx.storage.put('baseUrl', baseUrl);
|
|
149
|
+
} else {
|
|
150
|
+
if (this.baseUrl !== baseUrl) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
'Base URL already set and different from one previously provided'
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// RPC method to set the sleep timeout
|
|
159
|
+
async setSleepAfter(sleepAfter: string | number): Promise<void> {
|
|
160
|
+
this.sleepAfter = sleepAfter;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// RPC method to enable keepAlive mode
|
|
164
|
+
async setKeepAlive(keepAlive: boolean): Promise<void> {
|
|
165
|
+
this.keepAliveEnabled = keepAlive;
|
|
166
|
+
if (keepAlive) {
|
|
167
|
+
this.logger.info(
|
|
168
|
+
'KeepAlive mode enabled - container will stay alive until explicitly destroyed'
|
|
169
|
+
);
|
|
170
|
+
} else {
|
|
171
|
+
this.logger.info(
|
|
172
|
+
'KeepAlive mode disabled - container will timeout normally'
|
|
173
|
+
);
|
|
86
174
|
}
|
|
87
175
|
}
|
|
88
176
|
|
|
89
177
|
// RPC method to set environment variables
|
|
90
178
|
async setEnvVars(envVars: Record<string, string>): Promise<void> {
|
|
179
|
+
// Update local state for new sessions
|
|
91
180
|
this.envVars = { ...this.envVars, ...envVars };
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
// If we have a default session, update its environment too
|
|
181
|
+
|
|
182
|
+
// If default session already exists, update it directly
|
|
95
183
|
if (this.defaultSession) {
|
|
96
|
-
|
|
184
|
+
// Set environment variables by executing export commands in the existing session
|
|
185
|
+
for (const [key, value] of Object.entries(envVars)) {
|
|
186
|
+
const escapedValue = value.replace(/'/g, "'\\''");
|
|
187
|
+
const exportCommand = `export ${key}='${escapedValue}'`;
|
|
188
|
+
|
|
189
|
+
const result = await this.client.commands.execute(
|
|
190
|
+
exportCommand,
|
|
191
|
+
this.defaultSession
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
if (result.exitCode !== 0) {
|
|
195
|
+
throw new Error(
|
|
196
|
+
`Failed to set ${key}: ${result.stderr || 'Unknown error'}`
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
97
200
|
}
|
|
98
201
|
}
|
|
99
202
|
|
|
203
|
+
/**
|
|
204
|
+
* Cleanup and destroy the sandbox container
|
|
205
|
+
*/
|
|
206
|
+
override async destroy(): Promise<void> {
|
|
207
|
+
this.logger.info('Destroying sandbox container');
|
|
208
|
+
await super.destroy();
|
|
209
|
+
}
|
|
210
|
+
|
|
100
211
|
override onStart() {
|
|
101
|
-
|
|
212
|
+
this.logger.debug('Sandbox started');
|
|
213
|
+
|
|
214
|
+
// Check version compatibility asynchronously (don't block startup)
|
|
215
|
+
this.checkVersionCompatibility().catch((error) => {
|
|
216
|
+
this.logger.error(
|
|
217
|
+
'Version compatibility check failed',
|
|
218
|
+
error instanceof Error ? error : new Error(String(error))
|
|
219
|
+
);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Check if the container version matches the SDK version
|
|
225
|
+
* Logs a warning if there's a mismatch
|
|
226
|
+
*/
|
|
227
|
+
private async checkVersionCompatibility(): Promise<void> {
|
|
228
|
+
try {
|
|
229
|
+
// Get the SDK version (imported from version.ts)
|
|
230
|
+
const sdkVersion = SDK_VERSION;
|
|
231
|
+
|
|
232
|
+
// Get container version
|
|
233
|
+
const containerVersion = await this.client.utils.getVersion();
|
|
234
|
+
|
|
235
|
+
// If container version is unknown, it's likely an old container without the endpoint
|
|
236
|
+
if (containerVersion === 'unknown') {
|
|
237
|
+
this.logger.warn(
|
|
238
|
+
'Container version check: Container version could not be determined. ' +
|
|
239
|
+
'This may indicate an outdated container image. ' +
|
|
240
|
+
'Please update your container to match SDK version ' +
|
|
241
|
+
sdkVersion
|
|
242
|
+
);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Check if versions match
|
|
247
|
+
if (containerVersion !== sdkVersion) {
|
|
248
|
+
const message =
|
|
249
|
+
`Version mismatch detected! SDK version (${sdkVersion}) does not match ` +
|
|
250
|
+
`container version (${containerVersion}). This may cause compatibility issues. ` +
|
|
251
|
+
`Please update your container image to version ${sdkVersion}`;
|
|
252
|
+
|
|
253
|
+
// Log warning - we can't reliably detect dev vs prod environment in Durable Objects
|
|
254
|
+
// so we always use warning level as requested by the user
|
|
255
|
+
this.logger.warn(message);
|
|
256
|
+
} else {
|
|
257
|
+
this.logger.debug('Version check passed', {
|
|
258
|
+
sdkVersion,
|
|
259
|
+
containerVersion
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
} catch (error) {
|
|
263
|
+
// Don't fail the sandbox initialization if version check fails
|
|
264
|
+
this.logger.debug('Version compatibility check encountered an error', {
|
|
265
|
+
error: error instanceof Error ? error.message : String(error)
|
|
266
|
+
});
|
|
267
|
+
}
|
|
102
268
|
}
|
|
103
269
|
|
|
104
270
|
override onStop() {
|
|
105
|
-
|
|
271
|
+
this.logger.debug('Sandbox stopped');
|
|
106
272
|
}
|
|
107
273
|
|
|
108
274
|
override onError(error: unknown) {
|
|
109
|
-
|
|
275
|
+
this.logger.error(
|
|
276
|
+
'Sandbox error',
|
|
277
|
+
error instanceof Error ? error : new Error(String(error))
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled
|
|
283
|
+
* When keepAlive is disabled, calls parent implementation which stops the container
|
|
284
|
+
*/
|
|
285
|
+
override async onActivityExpired(): Promise<void> {
|
|
286
|
+
if (this.keepAliveEnabled) {
|
|
287
|
+
this.logger.debug(
|
|
288
|
+
'Activity expired but keepAlive is enabled - container will stay alive'
|
|
289
|
+
);
|
|
290
|
+
// Do nothing - don't call stop(), container stays alive
|
|
291
|
+
} else {
|
|
292
|
+
// Default behavior: stop the container
|
|
293
|
+
this.logger.debug('Activity expired - stopping container');
|
|
294
|
+
await super.onActivityExpired();
|
|
295
|
+
}
|
|
110
296
|
}
|
|
111
297
|
|
|
112
298
|
// Override fetch to route internal container requests to appropriate ports
|
|
113
299
|
override async fetch(request: Request): Promise<Response> {
|
|
114
|
-
|
|
300
|
+
// Extract or generate trace ID from request
|
|
301
|
+
const traceId =
|
|
302
|
+
TraceContext.fromHeaders(request.headers) || TraceContext.generate();
|
|
115
303
|
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
const name = request.headers.get("X-Sandbox-Name")!;
|
|
119
|
-
this.sandboxName = name;
|
|
120
|
-
await this.ctx.storage.put("sandboxName", name);
|
|
121
|
-
console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
|
|
122
|
-
}
|
|
304
|
+
// Create request-specific logger with trace ID
|
|
305
|
+
const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
|
|
123
306
|
|
|
124
|
-
|
|
125
|
-
|
|
307
|
+
return await runWithLogger(requestLogger, async () => {
|
|
308
|
+
const url = new URL(request.url);
|
|
126
309
|
|
|
127
|
-
|
|
128
|
-
|
|
310
|
+
// Capture and store the sandbox name from the header if present
|
|
311
|
+
if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
|
|
312
|
+
const name = request.headers.get('X-Sandbox-Name')!;
|
|
313
|
+
this.sandboxName = name;
|
|
314
|
+
await this.ctx.storage.put('sandboxName', name);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Detect WebSocket upgrade request (RFC 6455 compliant)
|
|
318
|
+
const upgradeHeader = request.headers.get('Upgrade');
|
|
319
|
+
const connectionHeader = request.headers.get('Connection');
|
|
320
|
+
const isWebSocket =
|
|
321
|
+
upgradeHeader?.toLowerCase() === 'websocket' &&
|
|
322
|
+
connectionHeader?.toLowerCase().includes('upgrade');
|
|
323
|
+
|
|
324
|
+
if (isWebSocket) {
|
|
325
|
+
// WebSocket path: Let parent Container class handle WebSocket proxying
|
|
326
|
+
// This bypasses containerFetch() which uses JSRPC and cannot handle WebSocket upgrades
|
|
327
|
+
try {
|
|
328
|
+
requestLogger.debug('WebSocket upgrade requested', {
|
|
329
|
+
path: url.pathname,
|
|
330
|
+
port: this.determinePort(url)
|
|
331
|
+
});
|
|
332
|
+
return await super.fetch(request);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
requestLogger.error(
|
|
335
|
+
'WebSocket connection failed',
|
|
336
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
337
|
+
{ path: url.pathname }
|
|
338
|
+
);
|
|
339
|
+
throw error;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Non-WebSocket: Use existing port determination and HTTP routing logic
|
|
344
|
+
const port = this.determinePort(url);
|
|
345
|
+
|
|
346
|
+
// Route to the appropriate port
|
|
347
|
+
return await this.containerFetch(request, port);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
wsConnect(request: Request, port: number): Promise<Response> {
|
|
352
|
+
// Dummy implementation that will be overridden by the stub
|
|
353
|
+
throw new Error('Not implemented here to avoid RPC serialization issues');
|
|
129
354
|
}
|
|
130
355
|
|
|
131
356
|
private determinePort(url: URL): number {
|
|
132
357
|
// Extract port from proxy requests (e.g., /proxy/8080/*)
|
|
133
358
|
const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
|
|
134
359
|
if (proxyMatch) {
|
|
135
|
-
return parseInt(proxyMatch[1]);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (url.port) {
|
|
139
|
-
return parseInt(url.port);
|
|
360
|
+
return parseInt(proxyMatch[1], 10);
|
|
140
361
|
}
|
|
141
362
|
|
|
142
363
|
// All other requests go to control plane on port 3000
|
|
@@ -144,283 +365,694 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
|
|
|
144
365
|
return 3000;
|
|
145
366
|
}
|
|
146
367
|
|
|
147
|
-
|
|
148
|
-
|
|
368
|
+
/**
|
|
369
|
+
* Ensure default session exists - lazy initialization
|
|
370
|
+
* This is called automatically by all public methods that need a session
|
|
371
|
+
*
|
|
372
|
+
* The session is persisted to Durable Object storage to survive hot reloads
|
|
373
|
+
* during development. If a session already exists in the container after reload,
|
|
374
|
+
* we reuse it instead of trying to create a new one.
|
|
375
|
+
*/
|
|
376
|
+
private async ensureDefaultSession(): Promise<string> {
|
|
149
377
|
if (!this.defaultSession) {
|
|
150
378
|
const sessionId = `sandbox-${this.sandboxName || 'default'}`;
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
379
|
+
|
|
380
|
+
try {
|
|
381
|
+
// Try to create session in container
|
|
382
|
+
await this.client.utils.createSession({
|
|
383
|
+
id: sessionId,
|
|
384
|
+
env: this.envVars || {},
|
|
385
|
+
cwd: '/workspace'
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
this.defaultSession = sessionId;
|
|
389
|
+
// Persist to storage so it survives hot reloads
|
|
390
|
+
await this.ctx.storage.put('defaultSession', sessionId);
|
|
391
|
+
this.logger.debug('Default session initialized', { sessionId });
|
|
392
|
+
} catch (error: any) {
|
|
393
|
+
// If session already exists (e.g., after hot reload), reuse it
|
|
394
|
+
if (error?.message?.includes('already exists')) {
|
|
395
|
+
this.logger.debug('Reusing existing session after reload', {
|
|
396
|
+
sessionId
|
|
397
|
+
});
|
|
398
|
+
this.defaultSession = sessionId;
|
|
399
|
+
// Persist to storage in case it wasn't saved before
|
|
400
|
+
await this.ctx.storage.put('defaultSession', sessionId);
|
|
401
|
+
} else {
|
|
402
|
+
// Re-throw other errors
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
158
406
|
}
|
|
159
407
|
return this.defaultSession;
|
|
160
408
|
}
|
|
161
409
|
|
|
162
|
-
|
|
410
|
+
// Enhanced exec method - always returns ExecResult with optional streaming
|
|
411
|
+
// This replaces the old exec method to match ISandbox interface
|
|
163
412
|
async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
|
|
164
413
|
const session = await this.ensureDefaultSession();
|
|
165
|
-
return
|
|
414
|
+
return this.execWithSession(command, session, options);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Internal session-aware exec implementation
|
|
419
|
+
* Used by both public exec() and session wrappers
|
|
420
|
+
*/
|
|
421
|
+
private async execWithSession(
|
|
422
|
+
command: string,
|
|
423
|
+
sessionId: string,
|
|
424
|
+
options?: ExecOptions
|
|
425
|
+
): Promise<ExecResult> {
|
|
426
|
+
const startTime = Date.now();
|
|
427
|
+
const timestamp = new Date().toISOString();
|
|
428
|
+
|
|
429
|
+
let timeoutId: NodeJS.Timeout | undefined;
|
|
430
|
+
|
|
431
|
+
try {
|
|
432
|
+
// Handle cancellation
|
|
433
|
+
if (options?.signal?.aborted) {
|
|
434
|
+
throw new Error('Operation was aborted');
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
let result: ExecResult;
|
|
438
|
+
|
|
439
|
+
if (options?.stream && options?.onOutput) {
|
|
440
|
+
// Streaming with callbacks - we need to collect the final result
|
|
441
|
+
result = await this.executeWithStreaming(
|
|
442
|
+
command,
|
|
443
|
+
sessionId,
|
|
444
|
+
options,
|
|
445
|
+
startTime,
|
|
446
|
+
timestamp
|
|
447
|
+
);
|
|
448
|
+
} else {
|
|
449
|
+
// Regular execution with session
|
|
450
|
+
const response = await this.client.commands.execute(command, sessionId);
|
|
451
|
+
|
|
452
|
+
const duration = Date.now() - startTime;
|
|
453
|
+
result = this.mapExecuteResponseToExecResult(
|
|
454
|
+
response,
|
|
455
|
+
duration,
|
|
456
|
+
sessionId
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// Call completion callback if provided
|
|
461
|
+
if (options?.onComplete) {
|
|
462
|
+
options.onComplete(result);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return result;
|
|
466
|
+
} catch (error) {
|
|
467
|
+
if (options?.onError && error instanceof Error) {
|
|
468
|
+
options.onError(error);
|
|
469
|
+
}
|
|
470
|
+
throw error;
|
|
471
|
+
} finally {
|
|
472
|
+
if (timeoutId) {
|
|
473
|
+
clearTimeout(timeoutId);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private async executeWithStreaming(
|
|
479
|
+
command: string,
|
|
480
|
+
sessionId: string,
|
|
481
|
+
options: ExecOptions,
|
|
482
|
+
startTime: number,
|
|
483
|
+
timestamp: string
|
|
484
|
+
): Promise<ExecResult> {
|
|
485
|
+
let stdout = '';
|
|
486
|
+
let stderr = '';
|
|
487
|
+
|
|
488
|
+
try {
|
|
489
|
+
const stream = await this.client.commands.executeStream(
|
|
490
|
+
command,
|
|
491
|
+
sessionId
|
|
492
|
+
);
|
|
493
|
+
|
|
494
|
+
for await (const event of parseSSEStream<ExecEvent>(stream)) {
|
|
495
|
+
// Check for cancellation
|
|
496
|
+
if (options.signal?.aborted) {
|
|
497
|
+
throw new Error('Operation was aborted');
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
switch (event.type) {
|
|
501
|
+
case 'stdout':
|
|
502
|
+
case 'stderr':
|
|
503
|
+
if (event.data) {
|
|
504
|
+
// Update accumulated output
|
|
505
|
+
if (event.type === 'stdout') stdout += event.data;
|
|
506
|
+
if (event.type === 'stderr') stderr += event.data;
|
|
507
|
+
|
|
508
|
+
// Call user's callback
|
|
509
|
+
if (options.onOutput) {
|
|
510
|
+
options.onOutput(event.type, event.data);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
break;
|
|
514
|
+
|
|
515
|
+
case 'complete': {
|
|
516
|
+
// Use result from complete event if available
|
|
517
|
+
const duration = Date.now() - startTime;
|
|
518
|
+
return {
|
|
519
|
+
success: (event.exitCode ?? 0) === 0,
|
|
520
|
+
exitCode: event.exitCode ?? 0,
|
|
521
|
+
stdout,
|
|
522
|
+
stderr,
|
|
523
|
+
command,
|
|
524
|
+
duration,
|
|
525
|
+
timestamp,
|
|
526
|
+
sessionId
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
case 'error':
|
|
531
|
+
throw new Error(event.data || 'Command execution failed');
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// If we get here without a complete event, something went wrong
|
|
536
|
+
throw new Error('Stream ended without completion event');
|
|
537
|
+
} catch (error) {
|
|
538
|
+
if (options.signal?.aborted) {
|
|
539
|
+
throw new Error('Operation was aborted');
|
|
540
|
+
}
|
|
541
|
+
throw error;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
private mapExecuteResponseToExecResult(
|
|
546
|
+
response: ExecuteResponse,
|
|
547
|
+
duration: number,
|
|
548
|
+
sessionId?: string
|
|
549
|
+
): ExecResult {
|
|
550
|
+
return {
|
|
551
|
+
success: response.success,
|
|
552
|
+
exitCode: response.exitCode,
|
|
553
|
+
stdout: response.stdout,
|
|
554
|
+
stderr: response.stderr,
|
|
555
|
+
command: response.command,
|
|
556
|
+
duration,
|
|
557
|
+
timestamp: response.timestamp,
|
|
558
|
+
sessionId
|
|
559
|
+
};
|
|
166
560
|
}
|
|
167
561
|
|
|
562
|
+
/**
|
|
563
|
+
* Create a Process domain object from HTTP client DTO
|
|
564
|
+
* Centralizes process object creation with bound methods
|
|
565
|
+
* This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
|
|
566
|
+
*/
|
|
567
|
+
private createProcessFromDTO(
|
|
568
|
+
data: {
|
|
569
|
+
id: string;
|
|
570
|
+
pid?: number;
|
|
571
|
+
command: string;
|
|
572
|
+
status: ProcessStatus;
|
|
573
|
+
startTime: string | Date;
|
|
574
|
+
endTime?: string | Date;
|
|
575
|
+
exitCode?: number;
|
|
576
|
+
},
|
|
577
|
+
sessionId: string
|
|
578
|
+
): Process {
|
|
579
|
+
return {
|
|
580
|
+
id: data.id,
|
|
581
|
+
pid: data.pid,
|
|
582
|
+
command: data.command,
|
|
583
|
+
status: data.status,
|
|
584
|
+
startTime:
|
|
585
|
+
typeof data.startTime === 'string'
|
|
586
|
+
? new Date(data.startTime)
|
|
587
|
+
: data.startTime,
|
|
588
|
+
endTime: data.endTime
|
|
589
|
+
? typeof data.endTime === 'string'
|
|
590
|
+
? new Date(data.endTime)
|
|
591
|
+
: data.endTime
|
|
592
|
+
: undefined,
|
|
593
|
+
exitCode: data.exitCode,
|
|
594
|
+
sessionId,
|
|
595
|
+
|
|
596
|
+
kill: async (signal?: string) => {
|
|
597
|
+
await this.killProcess(data.id, signal);
|
|
598
|
+
},
|
|
599
|
+
|
|
600
|
+
getStatus: async () => {
|
|
601
|
+
const current = await this.getProcess(data.id);
|
|
602
|
+
return current?.status || 'error';
|
|
603
|
+
},
|
|
604
|
+
|
|
605
|
+
getLogs: async () => {
|
|
606
|
+
const logs = await this.getProcessLogs(data.id);
|
|
607
|
+
return { stdout: logs.stdout, stderr: logs.stderr };
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Background process management
|
|
168
613
|
async startProcess(
|
|
169
614
|
command: string,
|
|
170
|
-
options?: ProcessOptions
|
|
615
|
+
options?: ProcessOptions,
|
|
616
|
+
sessionId?: string
|
|
171
617
|
): Promise<Process> {
|
|
172
|
-
|
|
173
|
-
|
|
618
|
+
// Use the new HttpClient method to start the process
|
|
619
|
+
try {
|
|
620
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
621
|
+
const response = await this.client.processes.startProcess(
|
|
622
|
+
command,
|
|
623
|
+
session,
|
|
624
|
+
{
|
|
625
|
+
processId: options?.processId
|
|
626
|
+
}
|
|
627
|
+
);
|
|
628
|
+
|
|
629
|
+
const processObj = this.createProcessFromDTO(
|
|
630
|
+
{
|
|
631
|
+
id: response.processId,
|
|
632
|
+
pid: response.pid,
|
|
633
|
+
command: response.command,
|
|
634
|
+
status: 'running' as ProcessStatus,
|
|
635
|
+
startTime: new Date(),
|
|
636
|
+
endTime: undefined,
|
|
637
|
+
exitCode: undefined
|
|
638
|
+
},
|
|
639
|
+
session
|
|
640
|
+
);
|
|
641
|
+
|
|
642
|
+
// Call onStart callback if provided
|
|
643
|
+
if (options?.onStart) {
|
|
644
|
+
options.onStart(processObj);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
return processObj;
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (options?.onError && error instanceof Error) {
|
|
650
|
+
options.onError(error);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
throw error;
|
|
654
|
+
}
|
|
174
655
|
}
|
|
175
656
|
|
|
176
|
-
async listProcesses(): Promise<Process[]> {
|
|
177
|
-
const session = await this.ensureDefaultSession();
|
|
178
|
-
|
|
657
|
+
async listProcesses(sessionId?: string): Promise<Process[]> {
|
|
658
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
659
|
+
const response = await this.client.processes.listProcesses();
|
|
660
|
+
|
|
661
|
+
return response.processes.map((processData) =>
|
|
662
|
+
this.createProcessFromDTO(
|
|
663
|
+
{
|
|
664
|
+
id: processData.id,
|
|
665
|
+
pid: processData.pid,
|
|
666
|
+
command: processData.command,
|
|
667
|
+
status: processData.status,
|
|
668
|
+
startTime: processData.startTime,
|
|
669
|
+
endTime: processData.endTime,
|
|
670
|
+
exitCode: processData.exitCode
|
|
671
|
+
},
|
|
672
|
+
session
|
|
673
|
+
)
|
|
674
|
+
);
|
|
179
675
|
}
|
|
180
676
|
|
|
181
|
-
async getProcess(id: string): Promise<Process | null> {
|
|
182
|
-
const session = await this.ensureDefaultSession();
|
|
183
|
-
|
|
677
|
+
async getProcess(id: string, sessionId?: string): Promise<Process | null> {
|
|
678
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
679
|
+
const response = await this.client.processes.getProcess(id);
|
|
680
|
+
if (!response.process) {
|
|
681
|
+
return null;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const processData = response.process;
|
|
685
|
+
return this.createProcessFromDTO(
|
|
686
|
+
{
|
|
687
|
+
id: processData.id,
|
|
688
|
+
pid: processData.pid,
|
|
689
|
+
command: processData.command,
|
|
690
|
+
status: processData.status,
|
|
691
|
+
startTime: processData.startTime,
|
|
692
|
+
endTime: processData.endTime,
|
|
693
|
+
exitCode: processData.exitCode
|
|
694
|
+
},
|
|
695
|
+
session
|
|
696
|
+
);
|
|
184
697
|
}
|
|
185
698
|
|
|
186
|
-
async killProcess(
|
|
187
|
-
|
|
188
|
-
|
|
699
|
+
async killProcess(
|
|
700
|
+
id: string,
|
|
701
|
+
signal?: string,
|
|
702
|
+
sessionId?: string
|
|
703
|
+
): Promise<void> {
|
|
704
|
+
// Note: signal parameter is not currently supported by the HttpClient implementation
|
|
705
|
+
// The HTTP client already throws properly typed errors, so we just let them propagate
|
|
706
|
+
await this.client.processes.killProcess(id);
|
|
189
707
|
}
|
|
190
708
|
|
|
191
|
-
async killAllProcesses(): Promise<number> {
|
|
192
|
-
const
|
|
193
|
-
return
|
|
709
|
+
async killAllProcesses(sessionId?: string): Promise<number> {
|
|
710
|
+
const response = await this.client.processes.killAllProcesses();
|
|
711
|
+
return response.cleanedCount;
|
|
194
712
|
}
|
|
195
713
|
|
|
196
|
-
async cleanupCompletedProcesses(): Promise<number> {
|
|
197
|
-
|
|
198
|
-
|
|
714
|
+
async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
|
|
715
|
+
// For now, this would need to be implemented as a container endpoint
|
|
716
|
+
// as we no longer maintain local process storage
|
|
717
|
+
// We'll return 0 as a placeholder until the container endpoint is added
|
|
718
|
+
return 0;
|
|
199
719
|
}
|
|
200
720
|
|
|
201
721
|
async getProcessLogs(
|
|
202
|
-
id: string
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
722
|
+
id: string,
|
|
723
|
+
sessionId?: string
|
|
724
|
+
): Promise<{ stdout: string; stderr: string; processId: string }> {
|
|
725
|
+
// The HTTP client already throws properly typed errors, so we just let them propagate
|
|
726
|
+
const response = await this.client.processes.getProcessLogs(id);
|
|
727
|
+
return {
|
|
728
|
+
stdout: response.stdout,
|
|
729
|
+
stderr: response.stderr,
|
|
730
|
+
processId: response.processId
|
|
731
|
+
};
|
|
206
732
|
}
|
|
207
733
|
|
|
208
|
-
// Streaming methods -
|
|
734
|
+
// Streaming methods - return ReadableStream for RPC compatibility
|
|
209
735
|
async execStream(
|
|
210
736
|
command: string,
|
|
211
737
|
options?: StreamOptions
|
|
212
738
|
): Promise<ReadableStream<Uint8Array>> {
|
|
739
|
+
// Check for cancellation
|
|
740
|
+
if (options?.signal?.aborted) {
|
|
741
|
+
throw new Error('Operation was aborted');
|
|
742
|
+
}
|
|
743
|
+
|
|
213
744
|
const session = await this.ensureDefaultSession();
|
|
214
|
-
|
|
745
|
+
// Get the stream from CommandClient
|
|
746
|
+
return this.client.commands.executeStream(command, session);
|
|
215
747
|
}
|
|
216
748
|
|
|
749
|
+
/**
|
|
750
|
+
* Internal session-aware execStream implementation
|
|
751
|
+
*/
|
|
752
|
+
private async execStreamWithSession(
|
|
753
|
+
command: string,
|
|
754
|
+
sessionId: string,
|
|
755
|
+
options?: StreamOptions
|
|
756
|
+
): Promise<ReadableStream<Uint8Array>> {
|
|
757
|
+
// Check for cancellation
|
|
758
|
+
if (options?.signal?.aborted) {
|
|
759
|
+
throw new Error('Operation was aborted');
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
return this.client.commands.executeStream(command, sessionId);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Stream logs from a background process as a ReadableStream.
|
|
767
|
+
*/
|
|
217
768
|
async streamProcessLogs(
|
|
218
769
|
processId: string,
|
|
219
770
|
options?: { signal?: AbortSignal }
|
|
220
771
|
): Promise<ReadableStream<Uint8Array>> {
|
|
221
|
-
|
|
222
|
-
|
|
772
|
+
// Check for cancellation
|
|
773
|
+
if (options?.signal?.aborted) {
|
|
774
|
+
throw new Error('Operation was aborted');
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
return this.client.processes.streamProcessLogs(processId);
|
|
223
778
|
}
|
|
224
779
|
|
|
225
780
|
async gitCheckout(
|
|
226
781
|
repoUrl: string,
|
|
227
|
-
options: { branch?: string; targetDir?: string }
|
|
782
|
+
options: { branch?: string; targetDir?: string; sessionId?: string }
|
|
228
783
|
) {
|
|
229
|
-
const session = await this.ensureDefaultSession();
|
|
230
|
-
return
|
|
784
|
+
const session = options.sessionId ?? (await this.ensureDefaultSession());
|
|
785
|
+
return this.client.git.checkout(repoUrl, session, {
|
|
786
|
+
branch: options.branch,
|
|
787
|
+
targetDir: options.targetDir
|
|
788
|
+
});
|
|
231
789
|
}
|
|
232
790
|
|
|
233
|
-
async mkdir(
|
|
234
|
-
|
|
235
|
-
|
|
791
|
+
async mkdir(
|
|
792
|
+
path: string,
|
|
793
|
+
options: { recursive?: boolean; sessionId?: string } = {}
|
|
794
|
+
) {
|
|
795
|
+
const session = options.sessionId ?? (await this.ensureDefaultSession());
|
|
796
|
+
return this.client.files.mkdir(path, session, {
|
|
797
|
+
recursive: options.recursive
|
|
798
|
+
});
|
|
236
799
|
}
|
|
237
800
|
|
|
238
801
|
async writeFile(
|
|
239
802
|
path: string,
|
|
240
803
|
content: string,
|
|
241
|
-
options: { encoding?: string } = {}
|
|
804
|
+
options: { encoding?: string; sessionId?: string } = {}
|
|
242
805
|
) {
|
|
243
|
-
const session = await this.ensureDefaultSession();
|
|
244
|
-
return
|
|
806
|
+
const session = options.sessionId ?? (await this.ensureDefaultSession());
|
|
807
|
+
return this.client.files.writeFile(path, content, session, {
|
|
808
|
+
encoding: options.encoding
|
|
809
|
+
});
|
|
245
810
|
}
|
|
246
811
|
|
|
247
|
-
async deleteFile(path: string) {
|
|
248
|
-
const session = await this.ensureDefaultSession();
|
|
249
|
-
return
|
|
812
|
+
async deleteFile(path: string, sessionId?: string) {
|
|
813
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
814
|
+
return this.client.files.deleteFile(path, session);
|
|
250
815
|
}
|
|
251
816
|
|
|
252
|
-
async renameFile(oldPath: string, newPath: string) {
|
|
253
|
-
const session = await this.ensureDefaultSession();
|
|
254
|
-
return
|
|
817
|
+
async renameFile(oldPath: string, newPath: string, sessionId?: string) {
|
|
818
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
819
|
+
return this.client.files.renameFile(oldPath, newPath, session);
|
|
255
820
|
}
|
|
256
821
|
|
|
257
|
-
async moveFile(
|
|
258
|
-
|
|
259
|
-
|
|
822
|
+
async moveFile(
|
|
823
|
+
sourcePath: string,
|
|
824
|
+
destinationPath: string,
|
|
825
|
+
sessionId?: string
|
|
826
|
+
) {
|
|
827
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
828
|
+
return this.client.files.moveFile(sourcePath, destinationPath, session);
|
|
260
829
|
}
|
|
261
830
|
|
|
262
|
-
async readFile(
|
|
263
|
-
|
|
264
|
-
|
|
831
|
+
async readFile(
|
|
832
|
+
path: string,
|
|
833
|
+
options: { encoding?: string; sessionId?: string } = {}
|
|
834
|
+
) {
|
|
835
|
+
const session = options.sessionId ?? (await this.ensureDefaultSession());
|
|
836
|
+
return this.client.files.readFile(path, session, {
|
|
837
|
+
encoding: options.encoding
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* Stream a file from the sandbox using Server-Sent Events
|
|
843
|
+
* Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
|
|
844
|
+
* @param path - Path to the file to stream
|
|
845
|
+
* @param options - Optional session ID
|
|
846
|
+
*/
|
|
847
|
+
async readFileStream(
|
|
848
|
+
path: string,
|
|
849
|
+
options: { sessionId?: string } = {}
|
|
850
|
+
): Promise<ReadableStream<Uint8Array>> {
|
|
851
|
+
const session = options.sessionId ?? (await this.ensureDefaultSession());
|
|
852
|
+
return this.client.files.readFileStream(path, session);
|
|
265
853
|
}
|
|
266
854
|
|
|
267
855
|
async listFiles(
|
|
268
856
|
path: string,
|
|
269
|
-
options
|
|
270
|
-
recursive?: boolean;
|
|
271
|
-
includeHidden?: boolean;
|
|
272
|
-
} = {}
|
|
857
|
+
options?: { recursive?: boolean; includeHidden?: boolean }
|
|
273
858
|
) {
|
|
274
859
|
const session = await this.ensureDefaultSession();
|
|
275
|
-
return
|
|
860
|
+
return this.client.files.listFiles(path, session, options);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
async exists(path: string, sessionId?: string) {
|
|
864
|
+
const session = sessionId ?? (await this.ensureDefaultSession());
|
|
865
|
+
return this.client.files.exists(path, session);
|
|
276
866
|
}
|
|
277
867
|
|
|
278
868
|
async exposePort(port: number, options: { name?: string; hostname: string }) {
|
|
279
|
-
|
|
869
|
+
// Check if hostname is workers.dev domain (doesn't support wildcard subdomains)
|
|
870
|
+
if (options.hostname.endsWith('.workers.dev')) {
|
|
871
|
+
const errorResponse: ErrorResponse = {
|
|
872
|
+
code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,
|
|
873
|
+
message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,
|
|
874
|
+
context: { originalError: options.hostname },
|
|
875
|
+
httpStatus: 400,
|
|
876
|
+
timestamp: new Date().toISOString()
|
|
877
|
+
};
|
|
878
|
+
throw new CustomDomainRequiredError(errorResponse);
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
const sessionId = await this.ensureDefaultSession();
|
|
882
|
+
await this.client.ports.exposePort(port, sessionId, options?.name);
|
|
280
883
|
|
|
281
884
|
// We need the sandbox name to construct preview URLs
|
|
282
885
|
if (!this.sandboxName) {
|
|
283
886
|
throw new Error(
|
|
284
|
-
|
|
887
|
+
'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
|
|
285
888
|
);
|
|
286
889
|
}
|
|
287
890
|
|
|
891
|
+
// Generate and store token for this port
|
|
892
|
+
const token = this.generatePortToken();
|
|
893
|
+
this.portTokens.set(port, token);
|
|
894
|
+
await this.persistPortTokens();
|
|
895
|
+
|
|
288
896
|
const url = this.constructPreviewUrl(
|
|
289
897
|
port,
|
|
290
898
|
this.sandboxName,
|
|
291
|
-
options.hostname
|
|
899
|
+
options.hostname,
|
|
900
|
+
token
|
|
292
901
|
);
|
|
293
902
|
|
|
294
903
|
return {
|
|
295
904
|
url,
|
|
296
905
|
port,
|
|
297
|
-
name: options?.name
|
|
906
|
+
name: options?.name
|
|
298
907
|
};
|
|
299
908
|
}
|
|
300
909
|
|
|
301
910
|
async unexposePort(port: number) {
|
|
302
911
|
if (!validatePort(port)) {
|
|
303
|
-
logSecurityEvent(
|
|
304
|
-
"INVALID_PORT_UNEXPOSE",
|
|
305
|
-
{
|
|
306
|
-
port,
|
|
307
|
-
},
|
|
308
|
-
"high"
|
|
309
|
-
);
|
|
310
912
|
throw new SecurityError(
|
|
311
913
|
`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
|
|
312
914
|
);
|
|
313
915
|
}
|
|
314
916
|
|
|
315
|
-
await this.
|
|
917
|
+
const sessionId = await this.ensureDefaultSession();
|
|
918
|
+
await this.client.ports.unexposePort(port, sessionId);
|
|
316
919
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
"low"
|
|
323
|
-
);
|
|
920
|
+
// Clean up token for this port
|
|
921
|
+
if (this.portTokens.has(port)) {
|
|
922
|
+
this.portTokens.delete(port);
|
|
923
|
+
await this.persistPortTokens();
|
|
924
|
+
}
|
|
324
925
|
}
|
|
325
926
|
|
|
326
927
|
async getExposedPorts(hostname: string) {
|
|
327
|
-
const
|
|
928
|
+
const sessionId = await this.ensureDefaultSession();
|
|
929
|
+
const response = await this.client.ports.getExposedPorts(sessionId);
|
|
328
930
|
|
|
329
931
|
// We need the sandbox name to construct preview URLs
|
|
330
932
|
if (!this.sandboxName) {
|
|
331
933
|
throw new Error(
|
|
332
|
-
|
|
934
|
+
'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
|
|
333
935
|
);
|
|
334
936
|
}
|
|
335
937
|
|
|
336
|
-
return response.ports.map((port) =>
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
938
|
+
return response.ports.map((port) => {
|
|
939
|
+
// Get token for this port - must exist for all exposed ports
|
|
940
|
+
const token = this.portTokens.get(port.port);
|
|
941
|
+
if (!token) {
|
|
942
|
+
throw new Error(
|
|
943
|
+
`Port ${port.port} is exposed but has no token. This should not happen.`
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
return {
|
|
948
|
+
url: this.constructPreviewUrl(
|
|
949
|
+
port.port,
|
|
950
|
+
this.sandboxName!,
|
|
951
|
+
hostname,
|
|
952
|
+
token
|
|
953
|
+
),
|
|
954
|
+
port: port.port,
|
|
955
|
+
status: port.status
|
|
956
|
+
};
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
async isPortExposed(port: number): Promise<boolean> {
|
|
961
|
+
try {
|
|
962
|
+
const sessionId = await this.ensureDefaultSession();
|
|
963
|
+
const response = await this.client.ports.getExposedPorts(sessionId);
|
|
964
|
+
return response.ports.some((exposedPort) => exposedPort.port === port);
|
|
965
|
+
} catch (error) {
|
|
966
|
+
this.logger.error(
|
|
967
|
+
'Error checking if port is exposed',
|
|
968
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
969
|
+
{ port }
|
|
970
|
+
);
|
|
971
|
+
return false;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
async validatePortToken(port: number, token: string): Promise<boolean> {
|
|
976
|
+
// First check if port is exposed
|
|
977
|
+
const isExposed = await this.isPortExposed(port);
|
|
978
|
+
if (!isExposed) {
|
|
979
|
+
return false;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// Get stored token for this port - must exist for all exposed ports
|
|
983
|
+
const storedToken = this.portTokens.get(port);
|
|
984
|
+
if (!storedToken) {
|
|
985
|
+
// This should not happen - all exposed ports must have tokens
|
|
986
|
+
this.logger.error(
|
|
987
|
+
'Port is exposed but has no token - bug detected',
|
|
988
|
+
undefined,
|
|
989
|
+
{ port }
|
|
990
|
+
);
|
|
991
|
+
return false;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
// Constant-time comparison to prevent timing attacks
|
|
995
|
+
return storedToken === token;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
private generatePortToken(): string {
|
|
999
|
+
// Generate cryptographically secure 16-character token using Web Crypto API
|
|
1000
|
+
// Available in Cloudflare Workers runtime
|
|
1001
|
+
const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)
|
|
1002
|
+
crypto.getRandomValues(array);
|
|
1003
|
+
|
|
1004
|
+
// Convert to base64url format (URL-safe, no padding, lowercase)
|
|
1005
|
+
const base64 = btoa(String.fromCharCode(...array));
|
|
1006
|
+
return base64
|
|
1007
|
+
.replace(/\+/g, '-')
|
|
1008
|
+
.replace(/\//g, '_')
|
|
1009
|
+
.replace(/=/g, '')
|
|
1010
|
+
.toLowerCase();
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
private async persistPortTokens(): Promise<void> {
|
|
1014
|
+
// Convert Map to plain object for storage
|
|
1015
|
+
const tokensObj: Record<string, string> = {};
|
|
1016
|
+
for (const [port, token] of this.portTokens.entries()) {
|
|
1017
|
+
tokensObj[port.toString()] = token;
|
|
1018
|
+
}
|
|
1019
|
+
await this.ctx.storage.put('portTokens', tokensObj);
|
|
342
1020
|
}
|
|
343
1021
|
|
|
344
1022
|
private constructPreviewUrl(
|
|
345
1023
|
port: number,
|
|
346
1024
|
sandboxId: string,
|
|
347
|
-
hostname: string
|
|
1025
|
+
hostname: string,
|
|
1026
|
+
token: string
|
|
348
1027
|
): string {
|
|
349
1028
|
if (!validatePort(port)) {
|
|
350
|
-
logSecurityEvent(
|
|
351
|
-
"INVALID_PORT_REJECTED",
|
|
352
|
-
{
|
|
353
|
-
port,
|
|
354
|
-
sandboxId,
|
|
355
|
-
hostname,
|
|
356
|
-
},
|
|
357
|
-
"high"
|
|
358
|
-
);
|
|
359
1029
|
throw new SecurityError(
|
|
360
1030
|
`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
|
|
361
1031
|
);
|
|
362
1032
|
}
|
|
363
1033
|
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
sanitizedSandboxId = sanitizeSandboxId(sandboxId);
|
|
367
|
-
} catch (error) {
|
|
368
|
-
logSecurityEvent(
|
|
369
|
-
"INVALID_SANDBOX_ID_REJECTED",
|
|
370
|
-
{
|
|
371
|
-
sandboxId,
|
|
372
|
-
port,
|
|
373
|
-
hostname,
|
|
374
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
375
|
-
},
|
|
376
|
-
"high"
|
|
377
|
-
);
|
|
378
|
-
throw error;
|
|
379
|
-
}
|
|
1034
|
+
// Validate sandbox ID (will throw SecurityError if invalid)
|
|
1035
|
+
const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
|
|
380
1036
|
|
|
381
1037
|
const isLocalhost = isLocalhostPattern(hostname);
|
|
382
1038
|
|
|
383
1039
|
if (isLocalhost) {
|
|
384
1040
|
// Unified subdomain approach for localhost (RFC 6761)
|
|
385
|
-
const [host, portStr] = hostname.split(
|
|
386
|
-
const mainPort = portStr ||
|
|
1041
|
+
const [host, portStr] = hostname.split(':');
|
|
1042
|
+
const mainPort = portStr || '80';
|
|
387
1043
|
|
|
388
1044
|
// Use URL constructor for safe URL building
|
|
389
1045
|
try {
|
|
390
1046
|
const baseUrl = new URL(`http://${host}:${mainPort}`);
|
|
391
|
-
// Construct subdomain safely
|
|
392
|
-
const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
|
|
1047
|
+
// Construct subdomain safely with mandatory token
|
|
1048
|
+
const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
|
|
393
1049
|
baseUrl.hostname = subdomainHost;
|
|
394
1050
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
logSecurityEvent(
|
|
398
|
-
"PREVIEW_URL_CONSTRUCTED",
|
|
399
|
-
{
|
|
400
|
-
port,
|
|
401
|
-
sandboxId: sanitizedSandboxId,
|
|
402
|
-
hostname,
|
|
403
|
-
resultUrl: finalUrl,
|
|
404
|
-
environment: "localhost",
|
|
405
|
-
},
|
|
406
|
-
"low"
|
|
407
|
-
);
|
|
408
|
-
|
|
409
|
-
return finalUrl;
|
|
1051
|
+
return baseUrl.toString();
|
|
410
1052
|
} catch (error) {
|
|
411
|
-
logSecurityEvent(
|
|
412
|
-
"URL_CONSTRUCTION_FAILED",
|
|
413
|
-
{
|
|
414
|
-
port,
|
|
415
|
-
sandboxId: sanitizedSandboxId,
|
|
416
|
-
hostname,
|
|
417
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
418
|
-
},
|
|
419
|
-
"high"
|
|
420
|
-
);
|
|
421
1053
|
throw new SecurityError(
|
|
422
1054
|
`Failed to construct preview URL: ${
|
|
423
|
-
error instanceof Error ? error.message :
|
|
1055
|
+
error instanceof Error ? error.message : 'Unknown error'
|
|
424
1056
|
}`
|
|
425
1057
|
);
|
|
426
1058
|
}
|
|
@@ -429,73 +1061,196 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
|
|
|
429
1061
|
// Production subdomain logic - enforce HTTPS
|
|
430
1062
|
try {
|
|
431
1063
|
// Always use HTTPS for production (non-localhost)
|
|
432
|
-
const protocol =
|
|
1064
|
+
const protocol = 'https';
|
|
433
1065
|
const baseUrl = new URL(`${protocol}://${hostname}`);
|
|
434
1066
|
|
|
435
|
-
// Construct subdomain safely
|
|
436
|
-
const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
|
|
1067
|
+
// Construct subdomain safely with mandatory token
|
|
1068
|
+
const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
|
|
437
1069
|
baseUrl.hostname = subdomainHost;
|
|
438
1070
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
logSecurityEvent(
|
|
442
|
-
"PREVIEW_URL_CONSTRUCTED",
|
|
443
|
-
{
|
|
444
|
-
port,
|
|
445
|
-
sandboxId: sanitizedSandboxId,
|
|
446
|
-
hostname,
|
|
447
|
-
resultUrl: finalUrl,
|
|
448
|
-
environment: "production",
|
|
449
|
-
},
|
|
450
|
-
"low"
|
|
451
|
-
);
|
|
452
|
-
|
|
453
|
-
return finalUrl;
|
|
1071
|
+
return baseUrl.toString();
|
|
454
1072
|
} catch (error) {
|
|
455
|
-
logSecurityEvent(
|
|
456
|
-
"URL_CONSTRUCTION_FAILED",
|
|
457
|
-
{
|
|
458
|
-
port,
|
|
459
|
-
sandboxId: sanitizedSandboxId,
|
|
460
|
-
hostname,
|
|
461
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
462
|
-
},
|
|
463
|
-
"high"
|
|
464
|
-
);
|
|
465
1073
|
throw new SecurityError(
|
|
466
1074
|
`Failed to construct preview URL: ${
|
|
467
|
-
error instanceof Error ? error.message :
|
|
1075
|
+
error instanceof Error ? error.message : 'Unknown error'
|
|
468
1076
|
}`
|
|
469
1077
|
);
|
|
470
1078
|
}
|
|
471
1079
|
}
|
|
472
1080
|
|
|
473
|
-
//
|
|
1081
|
+
// ============================================================================
|
|
1082
|
+
// Session Management - Advanced Use Cases
|
|
1083
|
+
// ============================================================================
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* Create isolated execution session for advanced use cases
|
|
1087
|
+
* Returns ExecutionSession with full sandbox API bound to specific session
|
|
1088
|
+
*/
|
|
1089
|
+
async createSession(options?: SessionOptions): Promise<ExecutionSession> {
|
|
1090
|
+
const sessionId = options?.id || `session-${Date.now()}`;
|
|
1091
|
+
|
|
1092
|
+
// Create session in container
|
|
1093
|
+
await this.client.utils.createSession({
|
|
1094
|
+
id: sessionId,
|
|
1095
|
+
env: options?.env,
|
|
1096
|
+
cwd: options?.cwd
|
|
1097
|
+
});
|
|
1098
|
+
|
|
1099
|
+
// Return wrapper that binds sessionId to all operations
|
|
1100
|
+
return this.getSessionWrapper(sessionId);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* Get an existing session by ID
|
|
1105
|
+
* Returns ExecutionSession wrapper bound to the specified session
|
|
1106
|
+
*
|
|
1107
|
+
* This is useful for retrieving sessions across different requests/contexts
|
|
1108
|
+
* without storing the ExecutionSession object (which has RPC lifecycle limitations)
|
|
1109
|
+
*
|
|
1110
|
+
* @param sessionId - The ID of an existing session
|
|
1111
|
+
* @returns ExecutionSession wrapper bound to the session
|
|
1112
|
+
*/
|
|
1113
|
+
async getSession(sessionId: string): Promise<ExecutionSession> {
|
|
1114
|
+
// No need to verify session exists in container - operations will fail naturally if it doesn't
|
|
1115
|
+
return this.getSessionWrapper(sessionId);
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/**
|
|
1119
|
+
* Delete an execution session
|
|
1120
|
+
* Cleans up session resources and removes it from the container
|
|
1121
|
+
* Note: Cannot delete the default session. To reset the default session,
|
|
1122
|
+
* use sandbox.destroy() to terminate the entire sandbox.
|
|
1123
|
+
*
|
|
1124
|
+
* @param sessionId - The ID of the session to delete
|
|
1125
|
+
* @returns Result with success status, sessionId, and timestamp
|
|
1126
|
+
* @throws Error if attempting to delete the default session
|
|
1127
|
+
*/
|
|
1128
|
+
async deleteSession(sessionId: string): Promise<SessionDeleteResult> {
|
|
1129
|
+
// Prevent deletion of default session
|
|
1130
|
+
if (this.defaultSession && sessionId === this.defaultSession) {
|
|
1131
|
+
throw new Error(
|
|
1132
|
+
`Cannot delete default session '${sessionId}'. Use sandbox.destroy() to terminate the sandbox.`
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const response = await this.client.utils.deleteSession(sessionId);
|
|
1137
|
+
|
|
1138
|
+
// Map HTTP response to result type
|
|
1139
|
+
return {
|
|
1140
|
+
success: response.success,
|
|
1141
|
+
sessionId: response.sessionId,
|
|
1142
|
+
timestamp: response.timestamp
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
474
1145
|
|
|
475
1146
|
/**
|
|
476
|
-
*
|
|
1147
|
+
* Internal helper to create ExecutionSession wrapper for a given sessionId
|
|
1148
|
+
* Used by both createSession and getSession
|
|
477
1149
|
*/
|
|
1150
|
+
private getSessionWrapper(sessionId: string): ExecutionSession {
|
|
1151
|
+
return {
|
|
1152
|
+
id: sessionId,
|
|
1153
|
+
|
|
1154
|
+
// Command execution - delegate to internal session-aware methods
|
|
1155
|
+
exec: (command, options) =>
|
|
1156
|
+
this.execWithSession(command, sessionId, options),
|
|
1157
|
+
execStream: (command, options) =>
|
|
1158
|
+
this.execStreamWithSession(command, sessionId, options),
|
|
1159
|
+
|
|
1160
|
+
// Process management
|
|
1161
|
+
startProcess: (command, options) =>
|
|
1162
|
+
this.startProcess(command, options, sessionId),
|
|
1163
|
+
listProcesses: () => this.listProcesses(sessionId),
|
|
1164
|
+
getProcess: (id) => this.getProcess(id, sessionId),
|
|
1165
|
+
killProcess: (id, signal) => this.killProcess(id, signal),
|
|
1166
|
+
killAllProcesses: () => this.killAllProcesses(),
|
|
1167
|
+
cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),
|
|
1168
|
+
getProcessLogs: (id) => this.getProcessLogs(id),
|
|
1169
|
+
streamProcessLogs: (processId, options) =>
|
|
1170
|
+
this.streamProcessLogs(processId, options),
|
|
1171
|
+
|
|
1172
|
+
// File operations - pass sessionId via options or parameter
|
|
1173
|
+
writeFile: (path, content, options) =>
|
|
1174
|
+
this.writeFile(path, content, { ...options, sessionId }),
|
|
1175
|
+
readFile: (path, options) =>
|
|
1176
|
+
this.readFile(path, { ...options, sessionId }),
|
|
1177
|
+
readFileStream: (path) => this.readFileStream(path, { sessionId }),
|
|
1178
|
+
mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),
|
|
1179
|
+
deleteFile: (path) => this.deleteFile(path, sessionId),
|
|
1180
|
+
renameFile: (oldPath, newPath) =>
|
|
1181
|
+
this.renameFile(oldPath, newPath, sessionId),
|
|
1182
|
+
moveFile: (sourcePath, destPath) =>
|
|
1183
|
+
this.moveFile(sourcePath, destPath, sessionId),
|
|
1184
|
+
listFiles: (path, options) =>
|
|
1185
|
+
this.client.files.listFiles(path, sessionId, options),
|
|
1186
|
+
exists: (path) => this.exists(path, sessionId),
|
|
1187
|
+
|
|
1188
|
+
// Git operations
|
|
1189
|
+
gitCheckout: (repoUrl, options) =>
|
|
1190
|
+
this.gitCheckout(repoUrl, { ...options, sessionId }),
|
|
1191
|
+
|
|
1192
|
+
// Environment management - needs special handling
|
|
1193
|
+
setEnvVars: async (envVars: Record<string, string>) => {
|
|
1194
|
+
try {
|
|
1195
|
+
// Set environment variables by executing export commands
|
|
1196
|
+
for (const [key, value] of Object.entries(envVars)) {
|
|
1197
|
+
const escapedValue = value.replace(/'/g, "'\\''");
|
|
1198
|
+
const exportCommand = `export ${key}='${escapedValue}'`;
|
|
1199
|
+
|
|
1200
|
+
const result = await this.client.commands.execute(
|
|
1201
|
+
exportCommand,
|
|
1202
|
+
sessionId
|
|
1203
|
+
);
|
|
1204
|
+
|
|
1205
|
+
if (result.exitCode !== 0) {
|
|
1206
|
+
throw new Error(
|
|
1207
|
+
`Failed to set ${key}: ${result.stderr || 'Unknown error'}`
|
|
1208
|
+
);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
} catch (error) {
|
|
1212
|
+
this.logger.error(
|
|
1213
|
+
'Failed to set environment variables',
|
|
1214
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
1215
|
+
{ sessionId }
|
|
1216
|
+
);
|
|
1217
|
+
throw error;
|
|
1218
|
+
}
|
|
1219
|
+
},
|
|
1220
|
+
|
|
1221
|
+
// Code interpreter methods - delegate to sandbox's code interpreter
|
|
1222
|
+
createCodeContext: (options) =>
|
|
1223
|
+
this.codeInterpreter.createCodeContext(options),
|
|
1224
|
+
runCode: async (code, options) => {
|
|
1225
|
+
const execution = await this.codeInterpreter.runCode(code, options);
|
|
1226
|
+
return execution.toJSON();
|
|
1227
|
+
},
|
|
1228
|
+
runCodeStream: (code, options) =>
|
|
1229
|
+
this.codeInterpreter.runCodeStream(code, options),
|
|
1230
|
+
listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
|
|
1231
|
+
deleteCodeContext: (contextId) =>
|
|
1232
|
+
this.codeInterpreter.deleteCodeContext(contextId)
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// ============================================================================
|
|
1237
|
+
// Code interpreter methods - delegate to CodeInterpreter wrapper
|
|
1238
|
+
// ============================================================================
|
|
1239
|
+
|
|
478
1240
|
async createCodeContext(
|
|
479
1241
|
options?: CreateContextOptions
|
|
480
1242
|
): Promise<CodeContext> {
|
|
481
1243
|
return this.codeInterpreter.createCodeContext(options);
|
|
482
1244
|
}
|
|
483
1245
|
|
|
484
|
-
/**
|
|
485
|
-
* Run code with streaming callbacks
|
|
486
|
-
*/
|
|
487
1246
|
async runCode(
|
|
488
1247
|
code: string,
|
|
489
1248
|
options?: RunCodeOptions
|
|
490
1249
|
): Promise<ExecutionResult> {
|
|
491
1250
|
const execution = await this.codeInterpreter.runCode(code, options);
|
|
492
|
-
// Convert to plain object for RPC serialization
|
|
493
1251
|
return execution.toJSON();
|
|
494
1252
|
}
|
|
495
1253
|
|
|
496
|
-
/**
|
|
497
|
-
* Run code and return a streaming response
|
|
498
|
-
*/
|
|
499
1254
|
async runCodeStream(
|
|
500
1255
|
code: string,
|
|
501
1256
|
options?: RunCodeOptions
|
|
@@ -503,245 +1258,11 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
|
|
|
503
1258
|
return this.codeInterpreter.runCodeStream(code, options);
|
|
504
1259
|
}
|
|
505
1260
|
|
|
506
|
-
/**
|
|
507
|
-
* List all code contexts
|
|
508
|
-
*/
|
|
509
1261
|
async listCodeContexts(): Promise<CodeContext[]> {
|
|
510
1262
|
return this.codeInterpreter.listCodeContexts();
|
|
511
1263
|
}
|
|
512
1264
|
|
|
513
|
-
/**
|
|
514
|
-
* Delete a code context
|
|
515
|
-
*/
|
|
516
1265
|
async deleteCodeContext(contextId: string): Promise<void> {
|
|
517
1266
|
return this.codeInterpreter.deleteCodeContext(contextId);
|
|
518
1267
|
}
|
|
519
|
-
|
|
520
|
-
// ============================================================================
|
|
521
|
-
// Session Management (Simple Isolation)
|
|
522
|
-
// ============================================================================
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Create a new execution session with isolation
|
|
526
|
-
* Returns a session object with exec() method
|
|
527
|
-
*/
|
|
528
|
-
|
|
529
|
-
async createSession(options: {
|
|
530
|
-
id?: string;
|
|
531
|
-
env?: Record<string, string>;
|
|
532
|
-
cwd?: string;
|
|
533
|
-
isolation?: boolean;
|
|
534
|
-
}): Promise<ExecutionSession> {
|
|
535
|
-
const sessionId = options.id || `session-${Date.now()}`;
|
|
536
|
-
|
|
537
|
-
await this.client.createSession({
|
|
538
|
-
id: sessionId,
|
|
539
|
-
env: options.env,
|
|
540
|
-
cwd: options.cwd,
|
|
541
|
-
isolation: options.isolation
|
|
542
|
-
});
|
|
543
|
-
// Return comprehensive ExecutionSession object that implements all ISandbox methods
|
|
544
|
-
return {
|
|
545
|
-
id: sessionId,
|
|
546
|
-
|
|
547
|
-
// Command execution - clean method names
|
|
548
|
-
exec: async (command: string, options?: ExecOptions) => {
|
|
549
|
-
const result = await this.client.exec(sessionId, command);
|
|
550
|
-
return {
|
|
551
|
-
...result,
|
|
552
|
-
command,
|
|
553
|
-
duration: 0,
|
|
554
|
-
timestamp: new Date().toISOString()
|
|
555
|
-
};
|
|
556
|
-
},
|
|
557
|
-
|
|
558
|
-
execStream: async (command: string, options?: StreamOptions) => {
|
|
559
|
-
return await this.client.execStream(sessionId, command);
|
|
560
|
-
},
|
|
561
|
-
|
|
562
|
-
// Process management - route to session-aware methods
|
|
563
|
-
startProcess: async (command: string, options?: ProcessOptions) => {
|
|
564
|
-
// Use session-specific process management
|
|
565
|
-
const response = await this.client.startProcess(command, sessionId, {
|
|
566
|
-
processId: options?.processId,
|
|
567
|
-
timeout: options?.timeout,
|
|
568
|
-
env: options?.env,
|
|
569
|
-
cwd: options?.cwd,
|
|
570
|
-
encoding: options?.encoding,
|
|
571
|
-
autoCleanup: options?.autoCleanup,
|
|
572
|
-
});
|
|
573
|
-
|
|
574
|
-
// Convert response to Process object with bound methods
|
|
575
|
-
const process = response.process;
|
|
576
|
-
return {
|
|
577
|
-
id: process.id,
|
|
578
|
-
pid: process.pid,
|
|
579
|
-
command: process.command,
|
|
580
|
-
status: process.status as ProcessStatus,
|
|
581
|
-
startTime: new Date(process.startTime),
|
|
582
|
-
endTime: process.endTime ? new Date(process.endTime) : undefined,
|
|
583
|
-
exitCode: process.exitCode ?? undefined,
|
|
584
|
-
kill: async (signal?: string) => {
|
|
585
|
-
await this.client.killProcess(process.id);
|
|
586
|
-
},
|
|
587
|
-
getStatus: async () => {
|
|
588
|
-
const resp = await this.client.getProcess(process.id);
|
|
589
|
-
return resp.process?.status as ProcessStatus || "error";
|
|
590
|
-
},
|
|
591
|
-
getLogs: async () => {
|
|
592
|
-
return await this.client.getProcessLogs(process.id);
|
|
593
|
-
},
|
|
594
|
-
};
|
|
595
|
-
},
|
|
596
|
-
|
|
597
|
-
listProcesses: async () => {
|
|
598
|
-
// Get processes for this specific session
|
|
599
|
-
const response = await this.client.listProcesses(sessionId);
|
|
600
|
-
|
|
601
|
-
// Convert to Process objects with bound methods
|
|
602
|
-
return response.processes.map(p => ({
|
|
603
|
-
id: p.id,
|
|
604
|
-
pid: p.pid,
|
|
605
|
-
command: p.command,
|
|
606
|
-
status: p.status as ProcessStatus,
|
|
607
|
-
startTime: new Date(p.startTime),
|
|
608
|
-
endTime: p.endTime ? new Date(p.endTime) : undefined,
|
|
609
|
-
exitCode: p.exitCode ?? undefined,
|
|
610
|
-
kill: async (signal?: string) => {
|
|
611
|
-
await this.client.killProcess(p.id);
|
|
612
|
-
},
|
|
613
|
-
getStatus: async () => {
|
|
614
|
-
const processResp = await this.client.getProcess(p.id);
|
|
615
|
-
return processResp.process?.status as ProcessStatus || "error";
|
|
616
|
-
},
|
|
617
|
-
getLogs: async () => {
|
|
618
|
-
return this.client.getProcessLogs(p.id);
|
|
619
|
-
},
|
|
620
|
-
}));
|
|
621
|
-
},
|
|
622
|
-
|
|
623
|
-
getProcess: async (id: string) => {
|
|
624
|
-
const response = await this.client.getProcess(id);
|
|
625
|
-
if (!response.process) return null;
|
|
626
|
-
|
|
627
|
-
const p = response.process;
|
|
628
|
-
return {
|
|
629
|
-
id: p.id,
|
|
630
|
-
pid: p.pid,
|
|
631
|
-
command: p.command,
|
|
632
|
-
status: p.status as ProcessStatus,
|
|
633
|
-
startTime: new Date(p.startTime),
|
|
634
|
-
endTime: p.endTime ? new Date(p.endTime) : undefined,
|
|
635
|
-
exitCode: p.exitCode ?? undefined,
|
|
636
|
-
kill: async (signal?: string) => {
|
|
637
|
-
await this.client.killProcess(p.id);
|
|
638
|
-
},
|
|
639
|
-
getStatus: async () => {
|
|
640
|
-
const processResp = await this.client.getProcess(p.id);
|
|
641
|
-
return processResp.process?.status as ProcessStatus || "error";
|
|
642
|
-
},
|
|
643
|
-
getLogs: async () => {
|
|
644
|
-
return this.client.getProcessLogs(p.id);
|
|
645
|
-
},
|
|
646
|
-
};
|
|
647
|
-
},
|
|
648
|
-
|
|
649
|
-
killProcess: async (id: string, signal?: string) => {
|
|
650
|
-
await this.client.killProcess(id);
|
|
651
|
-
},
|
|
652
|
-
|
|
653
|
-
killAllProcesses: async () => {
|
|
654
|
-
// Kill all processes for this specific session
|
|
655
|
-
const response = await this.client.killAllProcesses(sessionId);
|
|
656
|
-
return response.killedCount;
|
|
657
|
-
},
|
|
658
|
-
|
|
659
|
-
streamProcessLogs: async (processId: string, options?: { signal?: AbortSignal }) => {
|
|
660
|
-
return await this.client.streamProcessLogs(processId, options);
|
|
661
|
-
},
|
|
662
|
-
|
|
663
|
-
getProcessLogs: async (id: string) => {
|
|
664
|
-
return await this.client.getProcessLogs(id);
|
|
665
|
-
},
|
|
666
|
-
|
|
667
|
-
cleanupCompletedProcesses: async () => {
|
|
668
|
-
// This would need a new endpoint to cleanup processes for a specific session
|
|
669
|
-
// For now, return 0 as no cleanup is performed
|
|
670
|
-
return 0;
|
|
671
|
-
},
|
|
672
|
-
|
|
673
|
-
// File operations - clean method names (no "InSession" suffix)
|
|
674
|
-
writeFile: async (path: string, content: string, options?: { encoding?: string }) => {
|
|
675
|
-
return await this.client.writeFile(path, content, options?.encoding, sessionId);
|
|
676
|
-
},
|
|
677
|
-
|
|
678
|
-
readFile: async (path: string, options?: { encoding?: string }) => {
|
|
679
|
-
return await this.client.readFile(path, options?.encoding, sessionId);
|
|
680
|
-
},
|
|
681
|
-
|
|
682
|
-
mkdir: async (path: string, options?: { recursive?: boolean }) => {
|
|
683
|
-
return await this.client.mkdir(path, options?.recursive, sessionId);
|
|
684
|
-
},
|
|
685
|
-
|
|
686
|
-
deleteFile: async (path: string) => {
|
|
687
|
-
return await this.client.deleteFile(path, sessionId);
|
|
688
|
-
},
|
|
689
|
-
|
|
690
|
-
renameFile: async (oldPath: string, newPath: string) => {
|
|
691
|
-
return await this.client.renameFile(oldPath, newPath, sessionId);
|
|
692
|
-
},
|
|
693
|
-
|
|
694
|
-
moveFile: async (sourcePath: string, destinationPath: string) => {
|
|
695
|
-
return await this.client.moveFile(sourcePath, destinationPath, sessionId);
|
|
696
|
-
},
|
|
697
|
-
|
|
698
|
-
listFiles: async (path: string, options?: { recursive?: boolean; includeHidden?: boolean }) => {
|
|
699
|
-
return await this.client.listFiles(path, sessionId, options);
|
|
700
|
-
},
|
|
701
|
-
|
|
702
|
-
gitCheckout: async (repoUrl: string, options?: { branch?: string; targetDir?: string }) => {
|
|
703
|
-
return await this.client.gitCheckout(repoUrl, sessionId, options?.branch, options?.targetDir);
|
|
704
|
-
},
|
|
705
|
-
|
|
706
|
-
// Port management
|
|
707
|
-
exposePort: async (port: number, options: { name?: string; hostname: string }) => {
|
|
708
|
-
return await this.exposePort(port, options);
|
|
709
|
-
},
|
|
710
|
-
|
|
711
|
-
unexposePort: async (port: number) => {
|
|
712
|
-
return await this.unexposePort(port);
|
|
713
|
-
},
|
|
714
|
-
|
|
715
|
-
getExposedPorts: async (hostname: string) => {
|
|
716
|
-
return await this.getExposedPorts(hostname);
|
|
717
|
-
},
|
|
718
|
-
|
|
719
|
-
// Environment management
|
|
720
|
-
setEnvVars: async (envVars: Record<string, string>) => {
|
|
721
|
-
// TODO: Implement session-specific environment updates
|
|
722
|
-
console.log(`[Session ${sessionId}] Environment variables update not yet implemented`);
|
|
723
|
-
},
|
|
724
|
-
|
|
725
|
-
// Code Interpreter API
|
|
726
|
-
createCodeContext: async (options?: any) => {
|
|
727
|
-
return await this.createCodeContext(options);
|
|
728
|
-
},
|
|
729
|
-
|
|
730
|
-
runCode: async (code: string, options?: any) => {
|
|
731
|
-
return await this.runCode(code, options);
|
|
732
|
-
},
|
|
733
|
-
|
|
734
|
-
runCodeStream: async (code: string, options?: any) => {
|
|
735
|
-
return await this.runCodeStream(code, options);
|
|
736
|
-
},
|
|
737
|
-
|
|
738
|
-
listCodeContexts: async () => {
|
|
739
|
-
return await this.listCodeContexts();
|
|
740
|
-
},
|
|
741
|
-
|
|
742
|
-
deleteCodeContext: async (contextId: string) => {
|
|
743
|
-
return await this.deleteCodeContext(contextId);
|
|
744
|
-
}
|
|
745
|
-
};
|
|
746
|
-
}
|
|
747
1268
|
}
|