@cloudflare/sandbox 0.0.0-44e584c → 0.0.0-485cf61

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 (79) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/Dockerfile +160 -9
  3. package/README.md +149 -50
  4. package/dist/chunk-3NEP4CNV.js +99 -0
  5. package/dist/chunk-3NEP4CNV.js.map +1 -0
  6. package/dist/chunk-6IYG2RIN.js +117 -0
  7. package/dist/chunk-6IYG2RIN.js.map +1 -0
  8. package/dist/chunk-HB44YO2A.js +2331 -0
  9. package/dist/chunk-HB44YO2A.js.map +1 -0
  10. package/dist/chunk-KPVMMMIP.js +105 -0
  11. package/dist/chunk-KPVMMMIP.js.map +1 -0
  12. package/dist/chunk-NNGBXDMY.js +89 -0
  13. package/dist/chunk-NNGBXDMY.js.map +1 -0
  14. package/dist/file-stream.d.ts +43 -0
  15. package/dist/file-stream.js +9 -0
  16. package/dist/file-stream.js.map +1 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +55 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/interpreter.d.ts +33 -0
  21. package/dist/interpreter.js +8 -0
  22. package/dist/interpreter.js.map +1 -0
  23. package/dist/request-handler.d.ts +18 -0
  24. package/dist/request-handler.js +12 -0
  25. package/dist/request-handler.js.map +1 -0
  26. package/dist/sandbox-CtlKjZwf.d.ts +583 -0
  27. package/dist/sandbox.d.ts +4 -0
  28. package/dist/sandbox.js +12 -0
  29. package/dist/sandbox.js.map +1 -0
  30. package/dist/security.d.ts +35 -0
  31. package/dist/security.js +15 -0
  32. package/dist/security.js.map +1 -0
  33. package/dist/sse-parser.d.ts +28 -0
  34. package/dist/sse-parser.js +11 -0
  35. package/dist/sse-parser.js.map +1 -0
  36. package/package.json +11 -9
  37. package/src/clients/base-client.ts +297 -0
  38. package/src/clients/command-client.ts +118 -0
  39. package/src/clients/file-client.ts +272 -0
  40. package/src/clients/git-client.ts +95 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/clients/interpreter-client.ts +332 -0
  43. package/src/clients/port-client.ts +108 -0
  44. package/src/clients/process-client.ts +180 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +81 -0
  47. package/src/clients/utility-client.ts +97 -0
  48. package/src/errors/adapter.ts +180 -0
  49. package/src/errors/classes.ts +469 -0
  50. package/src/errors/index.ts +105 -0
  51. package/src/file-stream.ts +164 -0
  52. package/src/index.ts +83 -119
  53. package/src/interpreter.ts +159 -0
  54. package/src/request-handler.ts +198 -0
  55. package/src/sandbox.ts +959 -0
  56. package/src/security.ts +133 -0
  57. package/src/sse-parser.ts +147 -0
  58. package/startup.sh +7 -0
  59. package/tests/base-client.test.ts +328 -0
  60. package/tests/command-client.test.ts +407 -0
  61. package/tests/file-client.test.ts +643 -0
  62. package/tests/file-stream.test.ts +306 -0
  63. package/tests/git-client.test.ts +328 -0
  64. package/tests/port-client.test.ts +301 -0
  65. package/tests/process-client.test.ts +658 -0
  66. package/tests/sandbox.test.ts +465 -0
  67. package/tests/sse-parser.test.ts +291 -0
  68. package/tests/utility-client.test.ts +266 -0
  69. package/tests/wrangler.jsonc +35 -0
  70. package/tsconfig.json +9 -1
  71. package/vitest.config.ts +31 -0
  72. package/container_src/index.ts +0 -2906
  73. package/container_src/package.json +0 -9
  74. package/src/client.ts +0 -1950
  75. package/tests/client.example.ts +0 -308
  76. package/tests/connection-test.ts +0 -81
  77. package/tests/simple-test.ts +0 -81
  78. package/tests/test1.ts +0 -281
  79. package/tests/test2.ts +0 -929
@@ -0,0 +1,198 @@
1
+ import { getSandbox, type Sandbox } from "./sandbox";
2
+ import {
3
+ logSecurityEvent,
4
+ sanitizeSandboxId,
5
+ validatePort
6
+ } from "./security";
7
+
8
+ export interface SandboxEnv {
9
+ Sandbox: DurableObjectNamespace<Sandbox>;
10
+ }
11
+
12
+ export interface RouteInfo {
13
+ port: number;
14
+ sandboxId: string;
15
+ path: string;
16
+ token: string;
17
+ }
18
+
19
+ export async function proxyToSandbox<E extends SandboxEnv>(
20
+ request: Request,
21
+ env: E
22
+ ): Promise<Response | null> {
23
+ try {
24
+ const url = new URL(request.url);
25
+ const routeInfo = extractSandboxRoute(url);
26
+
27
+ if (!routeInfo) {
28
+ return null; // Not a request to an exposed container port
29
+ }
30
+
31
+ const { sandboxId, port, path, token } = routeInfo;
32
+ const sandbox = getSandbox(env.Sandbox, sandboxId);
33
+
34
+ // Critical security check: Validate token (mandatory for all user ports)
35
+ // Skip check for control plane port 3000
36
+ if (port !== 3000) {
37
+ // Validate the token matches the port
38
+ const isValidToken = await sandbox.validatePortToken(port, token);
39
+ if (!isValidToken) {
40
+ logSecurityEvent('INVALID_TOKEN_ACCESS_BLOCKED', {
41
+ port,
42
+ sandboxId,
43
+ path,
44
+ hostname: url.hostname,
45
+ url: request.url,
46
+ method: request.method,
47
+ userAgent: request.headers.get('User-Agent') || 'unknown'
48
+ }, 'high');
49
+
50
+ return new Response(
51
+ JSON.stringify({
52
+ error: `Access denied: Invalid token or port not exposed`,
53
+ code: 'INVALID_TOKEN'
54
+ }),
55
+ {
56
+ status: 404,
57
+ headers: {
58
+ 'Content-Type': 'application/json'
59
+ }
60
+ }
61
+ );
62
+ }
63
+ }
64
+
65
+ // Build proxy request with proper headers
66
+ let proxyUrl: string;
67
+
68
+ // Route based on the target port
69
+ if (port !== 3000) {
70
+ // Route directly to user's service on the specified port
71
+ proxyUrl = `http://localhost:${port}${path}${url.search}`;
72
+ } else {
73
+ // Port 3000 is our control plane - route normally
74
+ proxyUrl = `http://localhost:3000${path}${url.search}`;
75
+ }
76
+
77
+ const proxyRequest = new Request(proxyUrl, {
78
+ method: request.method,
79
+ headers: {
80
+ ...Object.fromEntries(request.headers),
81
+ 'X-Original-URL': request.url,
82
+ 'X-Forwarded-Host': url.hostname,
83
+ 'X-Forwarded-Proto': url.protocol.replace(':', ''),
84
+ 'X-Sandbox-Name': sandboxId, // Pass the friendly name
85
+ },
86
+ body: request.body,
87
+ // @ts-expect-error - duplex required for body streaming in modern runtimes
88
+ duplex: 'half',
89
+ });
90
+
91
+ return sandbox.containerFetch(proxyRequest, port);
92
+ } catch (error) {
93
+ console.error('[Sandbox] Proxy routing error:', error);
94
+ return new Response('Proxy routing error', { status: 500 });
95
+ }
96
+ }
97
+
98
+ function extractSandboxRoute(url: URL): RouteInfo | null {
99
+ // Parse subdomain pattern: port-sandboxId-token.domain (tokens mandatory)
100
+ const subdomainMatch = url.hostname.match(/^(\d{4,5})-([^.-][^.]*[^.-]|[^.-])-([a-zA-Z0-9_-]{12,20})\.(.+)$/);
101
+
102
+ if (!subdomainMatch) {
103
+ // Log malformed subdomain attempts
104
+ if (url.hostname.includes('-') && url.hostname.includes('.')) {
105
+ logSecurityEvent('MALFORMED_SUBDOMAIN_ATTEMPT', {
106
+ hostname: url.hostname,
107
+ url: url.toString()
108
+ }, 'medium');
109
+ }
110
+ return null;
111
+ }
112
+
113
+ const portStr = subdomainMatch[1];
114
+ const sandboxId = subdomainMatch[2];
115
+ const token = subdomainMatch[3]; // Mandatory token
116
+ const domain = subdomainMatch[4];
117
+
118
+ const port = parseInt(portStr, 10);
119
+ if (!validatePort(port)) {
120
+ logSecurityEvent('INVALID_PORT_IN_SUBDOMAIN', {
121
+ port,
122
+ portStr,
123
+ sandboxId,
124
+ hostname: url.hostname,
125
+ url: url.toString()
126
+ }, 'high');
127
+ return null;
128
+ }
129
+
130
+ let sanitizedSandboxId: string;
131
+ try {
132
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
133
+ } catch (error) {
134
+ logSecurityEvent('INVALID_SANDBOX_ID_IN_SUBDOMAIN', {
135
+ sandboxId,
136
+ port,
137
+ hostname: url.hostname,
138
+ url: url.toString(),
139
+ error: error instanceof Error ? error.message : 'Unknown error'
140
+ }, 'high');
141
+ return null;
142
+ }
143
+
144
+ // DNS subdomain length limit is 63 characters
145
+ if (sandboxId.length > 63) {
146
+ logSecurityEvent('SANDBOX_ID_LENGTH_VIOLATION', {
147
+ sandboxId,
148
+ length: sandboxId.length,
149
+ port,
150
+ hostname: url.hostname
151
+ }, 'medium');
152
+ return null;
153
+ }
154
+
155
+ logSecurityEvent('SANDBOX_ROUTE_EXTRACTED', {
156
+ port,
157
+ sandboxId: sanitizedSandboxId,
158
+ domain,
159
+ path: url.pathname || "/",
160
+ hostname: url.hostname,
161
+ hasToken: !!token
162
+ }, 'low');
163
+
164
+ return {
165
+ port,
166
+ sandboxId: sanitizedSandboxId,
167
+ path: url.pathname || "/",
168
+ token,
169
+ };
170
+ }
171
+
172
+ export function isLocalhostPattern(hostname: string): boolean {
173
+ // Handle IPv6 addresses in brackets (with or without port)
174
+ if (hostname.startsWith('[')) {
175
+ if (hostname.includes(']:')) {
176
+ // [::1]:port format
177
+ const ipv6Part = hostname.substring(0, hostname.indexOf(']:') + 1);
178
+ return ipv6Part === '[::1]';
179
+ } else {
180
+ // [::1] format without port
181
+ return hostname === '[::1]';
182
+ }
183
+ }
184
+
185
+ // Handle bare IPv6 without brackets
186
+ if (hostname === '::1') {
187
+ return true;
188
+ }
189
+
190
+ // For IPv4 and regular hostnames, split on colon to remove port
191
+ const hostPart = hostname.split(":")[0];
192
+
193
+ return (
194
+ hostPart === "localhost" ||
195
+ hostPart === "127.0.0.1" ||
196
+ hostPart === "0.0.0.0"
197
+ );
198
+ }