@cloudflare/sandbox 0.0.0-cecde0a → 0.0.0-d4bb3b7

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +314 -0
  2. package/Dockerfile +179 -69
  3. package/LICENSE +176 -0
  4. package/README.md +119 -315
  5. package/dist/index.d.ts +1953 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +3280 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +16 -7
  10. package/src/clients/base-client.ts +295 -0
  11. package/src/clients/command-client.ts +115 -0
  12. package/src/clients/file-client.ts +300 -0
  13. package/src/clients/git-client.ts +98 -0
  14. package/src/clients/index.ts +64 -0
  15. package/src/clients/interpreter-client.ts +333 -0
  16. package/src/clients/port-client.ts +105 -0
  17. package/src/clients/process-client.ts +180 -0
  18. package/src/clients/sandbox-client.ts +39 -0
  19. package/src/clients/types.ts +88 -0
  20. package/src/clients/utility-client.ts +156 -0
  21. package/src/errors/adapter.ts +238 -0
  22. package/src/errors/classes.ts +594 -0
  23. package/src/errors/index.ts +109 -0
  24. package/src/file-stream.ts +169 -0
  25. package/src/index.ts +98 -14
  26. package/src/interpreter.ts +168 -0
  27. package/src/request-handler.ts +94 -55
  28. package/src/sandbox.ts +938 -315
  29. package/src/security.ts +34 -28
  30. package/src/sse-parser.ts +8 -11
  31. package/src/version.ts +6 -0
  32. package/startup.sh +3 -0
  33. package/tests/base-client.test.ts +364 -0
  34. package/tests/command-client.test.ts +444 -0
  35. package/tests/file-client.test.ts +831 -0
  36. package/tests/file-stream.test.ts +310 -0
  37. package/tests/get-sandbox.test.ts +149 -0
  38. package/tests/git-client.test.ts +487 -0
  39. package/tests/port-client.test.ts +293 -0
  40. package/tests/process-client.test.ts +683 -0
  41. package/tests/request-handler.test.ts +292 -0
  42. package/tests/sandbox.test.ts +739 -0
  43. package/tests/sse-parser.test.ts +291 -0
  44. package/tests/utility-client.test.ts +339 -0
  45. package/tests/version.test.ts +16 -0
  46. package/tests/wrangler.jsonc +35 -0
  47. package/tsconfig.json +9 -1
  48. package/tsdown.config.ts +12 -0
  49. package/vitest.config.ts +31 -0
  50. package/container_src/handler/exec.ts +0 -337
  51. package/container_src/handler/file.ts +0 -844
  52. package/container_src/handler/git.ts +0 -182
  53. package/container_src/handler/ports.ts +0 -314
  54. package/container_src/handler/process.ts +0 -640
  55. package/container_src/index.ts +0 -361
  56. package/container_src/package.json +0 -9
  57. package/container_src/types.ts +0 -103
  58. package/src/client.ts +0 -1038
  59. package/src/types.ts +0 -386
@@ -0,0 +1,487 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import type { GitCheckoutResponse } from '../src/clients';
3
+ import { GitClient } from '../src/clients/git-client';
4
+ import {
5
+ GitAuthenticationError,
6
+ GitBranchNotFoundError,
7
+ GitCheckoutError,
8
+ GitCloneError,
9
+ GitError,
10
+ GitNetworkError,
11
+ GitRepositoryNotFoundError,
12
+ InvalidGitUrlError,
13
+ SandboxError
14
+ } from '../src/errors';
15
+
16
+ describe('GitClient', () => {
17
+ let client: GitClient;
18
+ let mockFetch: ReturnType<typeof vi.fn>;
19
+
20
+ beforeEach(() => {
21
+ vi.clearAllMocks();
22
+
23
+ mockFetch = vi.fn();
24
+ global.fetch = mockFetch as unknown as typeof fetch;
25
+
26
+ client = new GitClient({
27
+ baseUrl: 'http://test.com',
28
+ port: 3000
29
+ });
30
+ });
31
+
32
+ afterEach(() => {
33
+ vi.restoreAllMocks();
34
+ });
35
+
36
+ describe('repository cloning', () => {
37
+ it('should clone public repositories successfully', async () => {
38
+ const mockResponse: GitCheckoutResponse = {
39
+ success: true,
40
+ stdout:
41
+ "Cloning into 'react'...\nReceiving objects: 100% (1284/1284), done.",
42
+ stderr: '',
43
+ exitCode: 0,
44
+ repoUrl: 'https://github.com/facebook/react.git',
45
+ branch: 'main',
46
+ targetDir: 'react',
47
+ timestamp: '2023-01-01T00:00:00Z'
48
+ };
49
+
50
+ mockFetch.mockResolvedValue(
51
+ new Response(JSON.stringify(mockResponse), { status: 200 })
52
+ );
53
+
54
+ const result = await client.checkout(
55
+ 'https://github.com/facebook/react.git',
56
+ 'test-session'
57
+ );
58
+
59
+ expect(result.success).toBe(true);
60
+ expect(result.repoUrl).toBe('https://github.com/facebook/react.git');
61
+ expect(result.branch).toBe('main');
62
+ expect(result.exitCode).toBe(0);
63
+ });
64
+
65
+ it('should clone repositories to specific branches', async () => {
66
+ const mockResponse: GitCheckoutResponse = {
67
+ success: true,
68
+ stdout: "Cloning into 'project'...\nSwitching to branch 'development'",
69
+ stderr: '',
70
+ exitCode: 0,
71
+ repoUrl: 'https://github.com/company/project.git',
72
+ branch: 'development',
73
+ targetDir: 'project',
74
+ timestamp: '2023-01-01T00:00:00Z'
75
+ };
76
+
77
+ mockFetch.mockResolvedValue(
78
+ new Response(JSON.stringify(mockResponse), { status: 200 })
79
+ );
80
+
81
+ const result = await client.checkout(
82
+ 'https://github.com/company/project.git',
83
+ 'test-session',
84
+ { branch: 'development' }
85
+ );
86
+
87
+ expect(result.success).toBe(true);
88
+ expect(result.branch).toBe('development');
89
+ });
90
+
91
+ it('should clone repositories to custom directories', async () => {
92
+ const mockResponse: GitCheckoutResponse = {
93
+ success: true,
94
+ stdout: "Cloning into 'workspace/my-app'...\nDone.",
95
+ stderr: '',
96
+ exitCode: 0,
97
+ repoUrl: 'https://github.com/user/my-app.git',
98
+ branch: 'main',
99
+ targetDir: 'workspace/my-app',
100
+ timestamp: '2023-01-01T00:00:00Z'
101
+ };
102
+
103
+ mockFetch.mockResolvedValue(
104
+ new Response(JSON.stringify(mockResponse), { status: 200 })
105
+ );
106
+
107
+ const result = await client.checkout(
108
+ 'https://github.com/user/my-app.git',
109
+ 'test-session',
110
+ { targetDir: 'workspace/my-app' }
111
+ );
112
+
113
+ expect(result.success).toBe(true);
114
+ expect(result.targetDir).toBe('workspace/my-app');
115
+ });
116
+
117
+ it('should handle large repository clones with warnings', async () => {
118
+ const mockResponse: GitCheckoutResponse = {
119
+ success: true,
120
+ stdout:
121
+ "Cloning into 'linux'...\nReceiving objects: 100% (8125432/8125432), 2.34 GiB, done.",
122
+ stderr: 'warning: filtering not recognized by server',
123
+ exitCode: 0,
124
+ repoUrl: 'https://github.com/torvalds/linux.git',
125
+ branch: 'master',
126
+ targetDir: 'linux',
127
+ timestamp: '2023-01-01T00:05:30Z'
128
+ };
129
+
130
+ mockFetch.mockResolvedValue(
131
+ new Response(JSON.stringify(mockResponse), { status: 200 })
132
+ );
133
+
134
+ const result = await client.checkout(
135
+ 'https://github.com/torvalds/linux.git',
136
+ 'test-session'
137
+ );
138
+
139
+ expect(result.success).toBe(true);
140
+ expect(result.stderr).toContain('warning:');
141
+ });
142
+
143
+ it('should handle SSH repository URLs', async () => {
144
+ const mockResponse: GitCheckoutResponse = {
145
+ success: true,
146
+ stdout: "Cloning into 'private-project'...\nDone.",
147
+ stderr: '',
148
+ exitCode: 0,
149
+ repoUrl: 'git@github.com:company/private-project.git',
150
+ branch: 'main',
151
+ targetDir: 'private-project',
152
+ timestamp: '2023-01-01T00:00:00Z'
153
+ };
154
+
155
+ mockFetch.mockResolvedValue(
156
+ new Response(JSON.stringify(mockResponse), { status: 200 })
157
+ );
158
+
159
+ const result = await client.checkout(
160
+ 'git@github.com:company/private-project.git',
161
+ 'test-session'
162
+ );
163
+
164
+ expect(result.success).toBe(true);
165
+ expect(result.repoUrl).toBe('git@github.com:company/private-project.git');
166
+ });
167
+
168
+ it('should handle concurrent repository operations', async () => {
169
+ mockFetch.mockImplementation((url: string, options: RequestInit) => {
170
+ const body = JSON.parse(options.body as string);
171
+ const repoName = body.repoUrl.split('/').pop().replace('.git', '');
172
+
173
+ return Promise.resolve(
174
+ new Response(
175
+ JSON.stringify({
176
+ success: true,
177
+ stdout: `Cloning into '${repoName}'...\nDone.`,
178
+ stderr: '',
179
+ exitCode: 0,
180
+ repoUrl: body.repoUrl,
181
+ branch: body.branch || 'main',
182
+ targetDir: body.targetDir || repoName,
183
+ timestamp: new Date().toISOString()
184
+ })
185
+ )
186
+ );
187
+ });
188
+
189
+ const operations = await Promise.all([
190
+ client.checkout('https://github.com/facebook/react.git', 'session-1'),
191
+ client.checkout('https://github.com/microsoft/vscode.git', 'session-2'),
192
+ client.checkout('https://github.com/nodejs/node.git', 'session-3', {
193
+ branch: 'v18.x'
194
+ })
195
+ ]);
196
+
197
+ expect(operations).toHaveLength(3);
198
+ operations.forEach((result) => {
199
+ expect(result.success).toBe(true);
200
+ });
201
+ expect(mockFetch).toHaveBeenCalledTimes(3);
202
+ });
203
+ });
204
+
205
+ describe('repository error handling', () => {
206
+ it('should handle repository not found errors', async () => {
207
+ mockFetch.mockResolvedValue(
208
+ new Response(
209
+ JSON.stringify({
210
+ error: 'Repository not found',
211
+ code: 'GIT_REPOSITORY_NOT_FOUND'
212
+ }),
213
+ { status: 404 }
214
+ )
215
+ );
216
+
217
+ await expect(
218
+ client.checkout(
219
+ 'https://github.com/user/nonexistent.git',
220
+ 'test-session'
221
+ )
222
+ ).rejects.toThrow(GitRepositoryNotFoundError);
223
+ });
224
+
225
+ it('should handle authentication failures', async () => {
226
+ mockFetch.mockResolvedValue(
227
+ new Response(
228
+ JSON.stringify({
229
+ error: 'Authentication failed',
230
+ code: 'GIT_AUTH_FAILED'
231
+ }),
232
+ { status: 401 }
233
+ )
234
+ );
235
+
236
+ await expect(
237
+ client.checkout(
238
+ 'https://github.com/company/private.git',
239
+ 'test-session'
240
+ )
241
+ ).rejects.toThrow(GitAuthenticationError);
242
+ });
243
+
244
+ it('should handle branch not found errors', async () => {
245
+ mockFetch.mockResolvedValue(
246
+ new Response(
247
+ JSON.stringify({
248
+ error: 'Branch not found',
249
+ code: 'GIT_BRANCH_NOT_FOUND'
250
+ }),
251
+ { status: 404 }
252
+ )
253
+ );
254
+
255
+ await expect(
256
+ client.checkout('https://github.com/user/repo.git', 'test-session', {
257
+ branch: 'nonexistent-branch'
258
+ })
259
+ ).rejects.toThrow(GitBranchNotFoundError);
260
+ });
261
+
262
+ it('should handle network errors', async () => {
263
+ mockFetch.mockResolvedValue(
264
+ new Response(
265
+ JSON.stringify({ error: 'Network error', code: 'GIT_NETWORK_ERROR' }),
266
+ { status: 503 }
267
+ )
268
+ );
269
+
270
+ await expect(
271
+ client.checkout('https://github.com/user/repo.git', 'test-session')
272
+ ).rejects.toThrow(GitNetworkError);
273
+ });
274
+
275
+ it('should handle clone failures', async () => {
276
+ mockFetch.mockResolvedValue(
277
+ new Response(
278
+ JSON.stringify({ error: 'Clone failed', code: 'GIT_CLONE_FAILED' }),
279
+ { status: 507 }
280
+ )
281
+ );
282
+
283
+ await expect(
284
+ client.checkout(
285
+ 'https://github.com/large/repository.git',
286
+ 'test-session'
287
+ )
288
+ ).rejects.toThrow(GitCloneError);
289
+ });
290
+
291
+ it('should handle checkout failures', async () => {
292
+ mockFetch.mockResolvedValue(
293
+ new Response(
294
+ JSON.stringify({
295
+ error: 'Checkout failed',
296
+ code: 'GIT_CHECKOUT_FAILED'
297
+ }),
298
+ { status: 409 }
299
+ )
300
+ );
301
+
302
+ await expect(
303
+ client.checkout('https://github.com/user/repo.git', 'test-session', {
304
+ branch: 'feature-branch'
305
+ })
306
+ ).rejects.toThrow(GitCheckoutError);
307
+ });
308
+
309
+ it('should handle invalid Git URLs', async () => {
310
+ mockFetch.mockResolvedValue(
311
+ new Response(
312
+ JSON.stringify({ error: 'Invalid Git URL', code: 'INVALID_GIT_URL' }),
313
+ { status: 400 }
314
+ )
315
+ );
316
+
317
+ await expect(
318
+ client.checkout('not-a-valid-url', 'test-session')
319
+ ).rejects.toThrow(InvalidGitUrlError);
320
+ });
321
+
322
+ it('should handle partial clone failures', async () => {
323
+ const mockResponse: GitCheckoutResponse = {
324
+ success: false,
325
+ stdout: "Cloning into 'repo'...\nReceiving objects: 45% (450/1000)",
326
+ stderr: 'error: RPC failed\nfatal: early EOF',
327
+ exitCode: 128,
328
+ repoUrl: 'https://github.com/problematic/repo.git',
329
+ branch: 'main',
330
+ targetDir: 'repo',
331
+ timestamp: '2023-01-01T00:01:30Z'
332
+ };
333
+
334
+ mockFetch.mockResolvedValue(
335
+ new Response(JSON.stringify(mockResponse), { status: 200 })
336
+ );
337
+
338
+ const result = await client.checkout(
339
+ 'https://github.com/problematic/repo.git',
340
+ 'test-session'
341
+ );
342
+
343
+ expect(result.success).toBe(false);
344
+ expect(result.exitCode).toBe(128);
345
+ expect(result.stderr).toContain('RPC failed');
346
+ });
347
+ });
348
+
349
+ describe('error handling edge cases', () => {
350
+ it('should handle network failures', async () => {
351
+ mockFetch.mockRejectedValue(new Error('Network connection failed'));
352
+
353
+ await expect(
354
+ client.checkout('https://github.com/user/repo.git', 'test-session')
355
+ ).rejects.toThrow('Network connection failed');
356
+ });
357
+
358
+ it('should handle malformed server responses', async () => {
359
+ mockFetch.mockResolvedValue(
360
+ new Response('invalid json {', { status: 200 })
361
+ );
362
+
363
+ await expect(
364
+ client.checkout('https://github.com/user/repo.git', 'test-session')
365
+ ).rejects.toThrow(SandboxError);
366
+ });
367
+
368
+ it('should map server errors to client errors', async () => {
369
+ const serverErrorScenarios = [
370
+ { status: 400, code: 'INVALID_GIT_URL', error: InvalidGitUrlError },
371
+ { status: 401, code: 'GIT_AUTH_FAILED', error: GitAuthenticationError },
372
+ {
373
+ status: 404,
374
+ code: 'GIT_REPOSITORY_NOT_FOUND',
375
+ error: GitRepositoryNotFoundError
376
+ },
377
+ {
378
+ status: 404,
379
+ code: 'GIT_BRANCH_NOT_FOUND',
380
+ error: GitBranchNotFoundError
381
+ },
382
+ { status: 500, code: 'GIT_OPERATION_FAILED', error: GitError },
383
+ { status: 503, code: 'GIT_NETWORK_ERROR', error: GitNetworkError }
384
+ ];
385
+
386
+ for (const scenario of serverErrorScenarios) {
387
+ mockFetch.mockResolvedValueOnce(
388
+ new Response(
389
+ JSON.stringify({ error: 'Test error', code: scenario.code }),
390
+ { status: scenario.status }
391
+ )
392
+ );
393
+
394
+ await expect(
395
+ client.checkout('https://github.com/test/repo.git', 'test-session')
396
+ ).rejects.toThrow(scenario.error);
397
+ }
398
+ });
399
+ });
400
+
401
+ describe('constructor options', () => {
402
+ it('should initialize with minimal options', () => {
403
+ const minimalClient = new GitClient();
404
+ expect(minimalClient).toBeInstanceOf(GitClient);
405
+ });
406
+
407
+ it('should initialize with full options', () => {
408
+ const fullOptionsClient = new GitClient({
409
+ baseUrl: 'http://custom.com',
410
+ port: 8080
411
+ });
412
+ expect(fullOptionsClient).toBeInstanceOf(GitClient);
413
+ });
414
+ });
415
+
416
+ describe('credential redaction in logs', () => {
417
+ it('should redact credentials from URLs but leave public URLs unchanged', async () => {
418
+ const mockLogger = {
419
+ info: vi.fn(),
420
+ warn: vi.fn(),
421
+ error: vi.fn(),
422
+ debug: vi.fn(),
423
+ child: vi.fn()
424
+ };
425
+
426
+ const clientWithLogger = new GitClient({
427
+ baseUrl: 'http://test.com',
428
+ port: 3000,
429
+ logger: mockLogger
430
+ });
431
+
432
+ // Test with credentials
433
+ mockFetch.mockResolvedValueOnce(
434
+ new Response(
435
+ JSON.stringify({
436
+ success: true,
437
+ stdout: "Cloning into 'private-repo'...\nDone.",
438
+ stderr: '',
439
+ exitCode: 0,
440
+ repoUrl:
441
+ 'https://oauth2:ghp_token123@github.com/user/private-repo.git',
442
+ branch: 'main',
443
+ targetDir: '/workspace/private-repo',
444
+ timestamp: '2023-01-01T00:00:00Z'
445
+ }),
446
+ { status: 200 }
447
+ )
448
+ );
449
+
450
+ await clientWithLogger.checkout(
451
+ 'https://oauth2:ghp_token123@github.com/user/private-repo.git',
452
+ 'test-session'
453
+ );
454
+
455
+ let logDetails = mockLogger.info.mock.calls[0]?.[1]?.details;
456
+ expect(logDetails).not.toContain('ghp_token123');
457
+ expect(logDetails).toContain(
458
+ 'https://******@github.com/user/private-repo.git'
459
+ );
460
+
461
+ // Test without credentials
462
+ mockFetch.mockResolvedValueOnce(
463
+ new Response(
464
+ JSON.stringify({
465
+ success: true,
466
+ stdout: "Cloning into 'react'...\nDone.",
467
+ stderr: '',
468
+ exitCode: 0,
469
+ repoUrl: 'https://github.com/facebook/react.git',
470
+ branch: 'main',
471
+ targetDir: '/workspace/react',
472
+ timestamp: '2023-01-01T00:00:00Z'
473
+ }),
474
+ { status: 200 }
475
+ )
476
+ );
477
+
478
+ await clientWithLogger.checkout(
479
+ 'https://github.com/facebook/react.git',
480
+ 'test-session'
481
+ );
482
+
483
+ logDetails = mockLogger.info.mock.calls[1]?.[1]?.details;
484
+ expect(logDetails).toContain('https://github.com/facebook/react.git');
485
+ });
486
+ });
487
+ });