@cloudflare/sandbox 0.0.0-59da324 → 0.0.0-5d101e6

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 (88) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/Dockerfile +136 -9
  3. package/README.md +148 -49
  4. package/dist/chunk-BFVUNTP4.js +104 -0
  5. package/dist/chunk-BFVUNTP4.js.map +1 -0
  6. package/dist/chunk-E3RB3JOS.js +7 -0
  7. package/dist/chunk-E3RB3JOS.js.map +1 -0
  8. package/dist/chunk-EKSWCBCA.js +86 -0
  9. package/dist/chunk-EKSWCBCA.js.map +1 -0
  10. package/dist/chunk-I6PJN47O.js +2456 -0
  11. package/dist/chunk-I6PJN47O.js.map +1 -0
  12. package/dist/chunk-JXZMAU2C.js +559 -0
  13. package/dist/chunk-JXZMAU2C.js.map +1 -0
  14. package/dist/chunk-Z532A7QC.js +78 -0
  15. package/dist/chunk-Z532A7QC.js.map +1 -0
  16. package/dist/file-stream.d.ts +43 -0
  17. package/dist/file-stream.js +9 -0
  18. package/dist/file-stream.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.js +67 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/interpreter.d.ts +33 -0
  23. package/dist/interpreter.js +8 -0
  24. package/dist/interpreter.js.map +1 -0
  25. package/dist/request-handler.d.ts +18 -0
  26. package/dist/request-handler.js +13 -0
  27. package/dist/request-handler.js.map +1 -0
  28. package/dist/sandbox-DWQVgVTY.d.ts +603 -0
  29. package/dist/sandbox.d.ts +4 -0
  30. package/dist/sandbox.js +13 -0
  31. package/dist/sandbox.js.map +1 -0
  32. package/dist/security.d.ts +31 -0
  33. package/dist/security.js +13 -0
  34. package/dist/security.js.map +1 -0
  35. package/dist/sse-parser.d.ts +28 -0
  36. package/dist/sse-parser.js +11 -0
  37. package/dist/sse-parser.js.map +1 -0
  38. package/dist/version.d.ts +8 -0
  39. package/dist/version.js +7 -0
  40. package/dist/version.js.map +1 -0
  41. package/package.json +14 -8
  42. package/src/clients/base-client.ts +280 -0
  43. package/src/clients/command-client.ts +115 -0
  44. package/src/clients/file-client.ts +295 -0
  45. package/src/clients/git-client.ts +92 -0
  46. package/src/clients/index.ts +64 -0
  47. package/src/clients/interpreter-client.ts +329 -0
  48. package/src/clients/port-client.ts +105 -0
  49. package/src/clients/process-client.ts +177 -0
  50. package/src/clients/sandbox-client.ts +41 -0
  51. package/src/clients/types.ts +84 -0
  52. package/src/clients/utility-client.ts +119 -0
  53. package/src/errors/adapter.ts +180 -0
  54. package/src/errors/classes.ts +469 -0
  55. package/src/errors/index.ts +105 -0
  56. package/src/file-stream.ts +164 -0
  57. package/src/index.ts +83 -119
  58. package/src/interpreter.ts +159 -0
  59. package/src/request-handler.ts +180 -0
  60. package/src/sandbox.ts +1013 -0
  61. package/src/security.ts +104 -0
  62. package/src/sse-parser.ts +143 -0
  63. package/src/version.ts +6 -0
  64. package/startup.sh +3 -0
  65. package/tests/base-client.test.ts +328 -0
  66. package/tests/command-client.test.ts +407 -0
  67. package/tests/file-client.test.ts +719 -0
  68. package/tests/file-stream.test.ts +306 -0
  69. package/tests/get-sandbox.test.ts +110 -0
  70. package/tests/git-client.test.ts +328 -0
  71. package/tests/port-client.test.ts +301 -0
  72. package/tests/process-client.test.ts +658 -0
  73. package/tests/request-handler.test.ts +240 -0
  74. package/tests/sandbox.test.ts +554 -0
  75. package/tests/sse-parser.test.ts +290 -0
  76. package/tests/utility-client.test.ts +332 -0
  77. package/tests/version.test.ts +16 -0
  78. package/tests/wrangler.jsonc +35 -0
  79. package/tsconfig.json +9 -1
  80. package/vitest.config.ts +31 -0
  81. package/container_src/index.ts +0 -2900
  82. package/container_src/package.json +0 -9
  83. package/src/client.ts +0 -1929
  84. package/tests/client.example.ts +0 -308
  85. package/tests/connection-test.ts +0 -81
  86. package/tests/simple-test.ts +0 -81
  87. package/tests/test1.ts +0 -281
  88. package/tests/test2.ts +0 -929
@@ -0,0 +1,180 @@
1
+ import { createLogger, type LogContext, TraceContext } from "@repo/shared";
2
+ import { switchPort } from "@cloudflare/containers";
3
+ import { getSandbox, type Sandbox } from "./sandbox";
4
+ import {
5
+ sanitizeSandboxId,
6
+ validatePort
7
+ } from "./security";
8
+
9
+ export interface SandboxEnv {
10
+ Sandbox: DurableObjectNamespace<Sandbox>;
11
+ }
12
+
13
+ export interface RouteInfo {
14
+ port: number;
15
+ sandboxId: string;
16
+ path: string;
17
+ token: string;
18
+ }
19
+
20
+ export async function proxyToSandbox<E extends SandboxEnv>(
21
+ request: Request,
22
+ env: E
23
+ ): Promise<Response | null> {
24
+ // Create logger context for this request
25
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
26
+ const logger = createLogger({
27
+ component: 'sandbox-do',
28
+ traceId,
29
+ operation: 'proxy'
30
+ });
31
+
32
+ try {
33
+ const url = new URL(request.url);
34
+ const routeInfo = extractSandboxRoute(url);
35
+
36
+ if (!routeInfo) {
37
+ return null; // Not a request to an exposed container port
38
+ }
39
+
40
+ const { sandboxId, port, path, token } = routeInfo;
41
+ const sandbox = getSandbox(env.Sandbox, sandboxId);
42
+
43
+ // Critical security check: Validate token (mandatory for all user ports)
44
+ // Skip check for control plane port 3000
45
+ if (port !== 3000) {
46
+ // Validate the token matches the port
47
+ const isValidToken = await sandbox.validatePortToken(port, token);
48
+ if (!isValidToken) {
49
+ logger.warn('Invalid token access blocked', {
50
+ port,
51
+ sandboxId,
52
+ path,
53
+ hostname: url.hostname,
54
+ url: request.url,
55
+ method: request.method,
56
+ userAgent: request.headers.get('User-Agent') || 'unknown'
57
+ });
58
+
59
+ return new Response(
60
+ JSON.stringify({
61
+ error: `Access denied: Invalid token or port not exposed`,
62
+ code: 'INVALID_TOKEN'
63
+ }),
64
+ {
65
+ status: 404,
66
+ headers: {
67
+ 'Content-Type': 'application/json'
68
+ }
69
+ }
70
+ );
71
+ }
72
+ }
73
+
74
+ // Detect WebSocket upgrade request
75
+ const upgradeHeader = request.headers.get('Upgrade');
76
+ if (upgradeHeader?.toLowerCase() === 'websocket') {
77
+ // WebSocket path: Must use fetch() not containerFetch()
78
+ // This bypasses JSRPC serialization boundary which cannot handle WebSocket upgrades
79
+ return await sandbox.fetch(switchPort(request, port));
80
+ }
81
+
82
+ // Build proxy request with proper headers
83
+ let proxyUrl: string;
84
+
85
+ // Route based on the target port
86
+ if (port !== 3000) {
87
+ // Route directly to user's service on the specified port
88
+ proxyUrl = `http://localhost:${port}${path}${url.search}`;
89
+ } else {
90
+ // Port 3000 is our control plane - route normally
91
+ proxyUrl = `http://localhost:3000${path}${url.search}`;
92
+ }
93
+
94
+ const proxyRequest = new Request(proxyUrl, {
95
+ method: request.method,
96
+ headers: {
97
+ ...Object.fromEntries(request.headers),
98
+ 'X-Original-URL': request.url,
99
+ 'X-Forwarded-Host': url.hostname,
100
+ 'X-Forwarded-Proto': url.protocol.replace(':', ''),
101
+ 'X-Sandbox-Name': sandboxId, // Pass the friendly name
102
+ },
103
+ body: request.body,
104
+ // @ts-expect-error - duplex required for body streaming in modern runtimes
105
+ duplex: 'half',
106
+ });
107
+
108
+ return await sandbox.containerFetch(proxyRequest, port);
109
+ } catch (error) {
110
+ logger.error('Proxy routing error', error instanceof Error ? error : new Error(String(error)));
111
+ return new Response('Proxy routing error', { status: 500 });
112
+ }
113
+ }
114
+
115
+ function extractSandboxRoute(url: URL): RouteInfo | null {
116
+ // Parse subdomain pattern: port-sandboxId-token.domain (tokens mandatory)
117
+ // Token is always exactly 16 chars (generated by generatePortToken)
118
+ const subdomainMatch = url.hostname.match(/^(\d{4,5})-([^.-][^.]*?[^.-]|[^.-])-([a-z0-9_-]{16})\.(.+)$/);
119
+
120
+ if (!subdomainMatch) {
121
+ return null;
122
+ }
123
+
124
+ const portStr = subdomainMatch[1];
125
+ const sandboxId = subdomainMatch[2];
126
+ const token = subdomainMatch[3]; // Mandatory token
127
+ const domain = subdomainMatch[4];
128
+
129
+ const port = parseInt(portStr, 10);
130
+ if (!validatePort(port)) {
131
+ return null;
132
+ }
133
+
134
+ let sanitizedSandboxId: string;
135
+ try {
136
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
137
+ } catch (error) {
138
+ return null;
139
+ }
140
+
141
+ // DNS subdomain length limit is 63 characters
142
+ if (sandboxId.length > 63) {
143
+ return null;
144
+ }
145
+
146
+ return {
147
+ port,
148
+ sandboxId: sanitizedSandboxId,
149
+ path: url.pathname || "/",
150
+ token,
151
+ };
152
+ }
153
+
154
+ export function isLocalhostPattern(hostname: string): boolean {
155
+ // Handle IPv6 addresses in brackets (with or without port)
156
+ if (hostname.startsWith('[')) {
157
+ if (hostname.includes(']:')) {
158
+ // [::1]:port format
159
+ const ipv6Part = hostname.substring(0, hostname.indexOf(']:') + 1);
160
+ return ipv6Part === '[::1]';
161
+ } else {
162
+ // [::1] format without port
163
+ return hostname === '[::1]';
164
+ }
165
+ }
166
+
167
+ // Handle bare IPv6 without brackets
168
+ if (hostname === '::1') {
169
+ return true;
170
+ }
171
+
172
+ // For IPv4 and regular hostnames, split on colon to remove port
173
+ const hostPart = hostname.split(":")[0];
174
+
175
+ return (
176
+ hostPart === "localhost" ||
177
+ hostPart === "127.0.0.1" ||
178
+ hostPart === "0.0.0.0"
179
+ );
180
+ }