@cloudflare/sandbox 0.0.0-60af265 → 0.0.0-633bd10

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 +189 -0
  2. package/Dockerfile +166 -9
  3. package/README.md +149 -50
  4. package/dist/chunk-BCJ7SF3Q.js +117 -0
  5. package/dist/chunk-BCJ7SF3Q.js.map +1 -0
  6. package/dist/chunk-BFVUNTP4.js +104 -0
  7. package/dist/chunk-BFVUNTP4.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-HGF554LH.js +2236 -0
  11. package/dist/chunk-HGF554LH.js.map +1 -0
  12. package/dist/chunk-Z532A7QC.js +78 -0
  13. package/dist/chunk-Z532A7QC.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-D9K2ypln.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 +31 -0
  31. package/dist/security.js +13 -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 +280 -0
  38. package/src/clients/command-client.ts +115 -0
  39. package/src/clients/file-client.ts +269 -0
  40. package/src/clients/git-client.ts +92 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/clients/interpreter-client.ts +329 -0
  43. package/src/clients/port-client.ts +105 -0
  44. package/src/clients/process-client.ts +177 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +84 -0
  47. package/src/clients/utility-client.ts +94 -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 -126
  53. package/src/interpreter.ts +159 -0
  54. package/src/request-handler.ts +170 -0
  55. package/src/sandbox.ts +917 -0
  56. package/src/security.ts +104 -0
  57. package/src/sse-parser.ts +143 -0
  58. package/startup.sh +3 -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 +290 -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 -1960
  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,170 @@
1
+ import { createLogger, type LogContext, TraceContext } from "@repo/shared";
2
+ import { getSandbox, type Sandbox } from "./sandbox";
3
+ import {
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
+ // Create logger context for this request
24
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
25
+ const logger = createLogger({
26
+ component: 'sandbox-do',
27
+ traceId,
28
+ operation: 'proxy'
29
+ });
30
+
31
+ try {
32
+ const url = new URL(request.url);
33
+ const routeInfo = extractSandboxRoute(url);
34
+
35
+ if (!routeInfo) {
36
+ return null; // Not a request to an exposed container port
37
+ }
38
+
39
+ const { sandboxId, port, path, token } = routeInfo;
40
+ const sandbox = getSandbox(env.Sandbox, sandboxId);
41
+
42
+ // Critical security check: Validate token (mandatory for all user ports)
43
+ // Skip check for control plane port 3000
44
+ if (port !== 3000) {
45
+ // Validate the token matches the port
46
+ const isValidToken = await sandbox.validatePortToken(port, token);
47
+ if (!isValidToken) {
48
+ logger.warn('Invalid token access blocked', {
49
+ port,
50
+ sandboxId,
51
+ path,
52
+ hostname: url.hostname,
53
+ url: request.url,
54
+ method: request.method,
55
+ userAgent: request.headers.get('User-Agent') || 'unknown'
56
+ });
57
+
58
+ return new Response(
59
+ JSON.stringify({
60
+ error: `Access denied: Invalid token or port not exposed`,
61
+ code: 'INVALID_TOKEN'
62
+ }),
63
+ {
64
+ status: 404,
65
+ headers: {
66
+ 'Content-Type': 'application/json'
67
+ }
68
+ }
69
+ );
70
+ }
71
+ }
72
+
73
+ // Build proxy request with proper headers
74
+ let proxyUrl: string;
75
+
76
+ // Route based on the target port
77
+ if (port !== 3000) {
78
+ // Route directly to user's service on the specified port
79
+ proxyUrl = `http://localhost:${port}${path}${url.search}`;
80
+ } else {
81
+ // Port 3000 is our control plane - route normally
82
+ proxyUrl = `http://localhost:3000${path}${url.search}`;
83
+ }
84
+
85
+ const proxyRequest = new Request(proxyUrl, {
86
+ method: request.method,
87
+ headers: {
88
+ ...Object.fromEntries(request.headers),
89
+ 'X-Original-URL': request.url,
90
+ 'X-Forwarded-Host': url.hostname,
91
+ 'X-Forwarded-Proto': url.protocol.replace(':', ''),
92
+ 'X-Sandbox-Name': sandboxId, // Pass the friendly name
93
+ },
94
+ body: request.body,
95
+ // @ts-expect-error - duplex required for body streaming in modern runtimes
96
+ duplex: 'half',
97
+ });
98
+
99
+ return sandbox.containerFetch(proxyRequest, port);
100
+ } catch (error) {
101
+ logger.error('Proxy routing error', error instanceof Error ? error : new Error(String(error)));
102
+ return new Response('Proxy routing error', { status: 500 });
103
+ }
104
+ }
105
+
106
+ function extractSandboxRoute(url: URL): RouteInfo | null {
107
+ // Parse subdomain pattern: port-sandboxId-token.domain (tokens mandatory)
108
+ const subdomainMatch = url.hostname.match(/^(\d{4,5})-([^.-][^.]*[^.-]|[^.-])-([a-zA-Z0-9_-]{12,20})\.(.+)$/);
109
+
110
+ if (!subdomainMatch) {
111
+ return null;
112
+ }
113
+
114
+ const portStr = subdomainMatch[1];
115
+ const sandboxId = subdomainMatch[2];
116
+ const token = subdomainMatch[3]; // Mandatory token
117
+ const domain = subdomainMatch[4];
118
+
119
+ const port = parseInt(portStr, 10);
120
+ if (!validatePort(port)) {
121
+ return null;
122
+ }
123
+
124
+ let sanitizedSandboxId: string;
125
+ try {
126
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
127
+ } catch (error) {
128
+ return null;
129
+ }
130
+
131
+ // DNS subdomain length limit is 63 characters
132
+ if (sandboxId.length > 63) {
133
+ return null;
134
+ }
135
+
136
+ return {
137
+ port,
138
+ sandboxId: sanitizedSandboxId,
139
+ path: url.pathname || "/",
140
+ token,
141
+ };
142
+ }
143
+
144
+ export function isLocalhostPattern(hostname: string): boolean {
145
+ // Handle IPv6 addresses in brackets (with or without port)
146
+ if (hostname.startsWith('[')) {
147
+ if (hostname.includes(']:')) {
148
+ // [::1]:port format
149
+ const ipv6Part = hostname.substring(0, hostname.indexOf(']:') + 1);
150
+ return ipv6Part === '[::1]';
151
+ } else {
152
+ // [::1] format without port
153
+ return hostname === '[::1]';
154
+ }
155
+ }
156
+
157
+ // Handle bare IPv6 without brackets
158
+ if (hostname === '::1') {
159
+ return true;
160
+ }
161
+
162
+ // For IPv4 and regular hostnames, split on colon to remove port
163
+ const hostPart = hostname.split(":")[0];
164
+
165
+ return (
166
+ hostPart === "localhost" ||
167
+ hostPart === "127.0.0.1" ||
168
+ hostPart === "0.0.0.0"
169
+ );
170
+ }