huaweicloud-devkit 2.0.1-next.2 → 2.0.1-next.4
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/README.md +26 -3
- package/README.zh-CN.md +24 -1
- package/package.json +1 -1
- package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.mcp.json +3 -0
- package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/dist/approval-roster.js +2 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +7 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +30 -1
- package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +21 -0
- package/plugins/huaweicloud-core/dist/mcp-server.js +4227 -3049
- package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
- package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +13 -2
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +198 -10
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +11 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +22 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +46 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +11 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +20 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +26 -18
- package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +97 -0
- package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +30 -14
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-backend.js +37 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-connections.js +84 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-client.js +229 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-protocol.js +151 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-transport.js +121 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-service-api.js +80 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-upload.js +106 -0
- package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +12 -0
- package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +5 -2
- package/plugins/huaweicloud-core/dist/server-install.js +363 -0
- package/plugins/huaweicloud-core/dist/setup-cli.js +16 -0
- package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
- package/plugins/huaweicloud-core/dist/tools.js +1 -0
- package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
- package/plugins/huaweicloud-core/safety/policy.json +2 -1
- package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +67 -16
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/devbox-backend.md +78 -0
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +14 -0
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +2 -1
- package/plugins/huaweicloud-core/src/approval-roster.ts +2 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +7 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +30 -1
- package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +22 -0
- package/plugins/huaweicloud-core/src/mcp-server-remote.ts +68 -5
- package/plugins/huaweicloud-core/src/mcp-server.ts +4 -1
- package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +15 -2
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +206 -11
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +12 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +23 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +49 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +11 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +23 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +27 -17
- package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +105 -0
- package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +36 -18
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-backend.ts +44 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-connections.ts +115 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-client.ts +281 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-protocol.ts +180 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-transport.ts +142 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-service-api.ts +102 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-upload.ts +167 -0
- package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +12 -0
- package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +5 -2
- package/plugins/huaweicloud-core/src/server-install.ts +442 -0
- package/plugins/huaweicloud-core/src/setup-cli.ts +16 -0
- package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
- package/plugins/huaweicloud-core/src/tools.ts +3 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// DevBox EnvD data-plane client (one-shot only): Process/Start (non-PTY),
|
|
2
|
+
// /files read/write, and a stat helper. No PTY, no Process/Connect, no
|
|
3
|
+
// SendInput/SendSignal — the v1 scope pinned by the design.
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import { ConnectFrameDecoder, ENVD_API_PORT, PROCESS_START_PATH, assertConnectContentType, buildProcessStartRequest, decodeProcessChunk, deriveAppPortUrl, encodeConnectFrame, parseProcessEvent, } from "./devbox-envd-protocol.js";
|
|
6
|
+
import { devboxFetch, rewriteDevboxUrl } from "./devbox-envd-transport.js";
|
|
7
|
+
export class DevboxEnvdHttpError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
auth;
|
|
10
|
+
detail;
|
|
11
|
+
constructor(status, message, detail) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'DevboxEnvdHttpError';
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.auth = status === 401 || status === 403;
|
|
16
|
+
this.detail = detail;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function envdHeaders(connection) {
|
|
20
|
+
const headers = {
|
|
21
|
+
Cookie: `relay_token=${connection.connectToken}`,
|
|
22
|
+
'E2B-Sandbox-Id': connection.sandboxId,
|
|
23
|
+
'E2B-Sandbox-Port': String(ENVD_API_PORT),
|
|
24
|
+
};
|
|
25
|
+
if (connection.envdAccessToken)
|
|
26
|
+
headers['X-Access-Token'] = connection.envdAccessToken;
|
|
27
|
+
return headers;
|
|
28
|
+
}
|
|
29
|
+
function timeoutError(timeoutMs) {
|
|
30
|
+
return Object.assign(new Error(`sandbox exec: command timed out after ${timeoutMs}ms (the remote process may still be running).`), { exitCode: 124, timeout: true });
|
|
31
|
+
}
|
|
32
|
+
function isAbort(error) {
|
|
33
|
+
return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');
|
|
34
|
+
}
|
|
35
|
+
async function responseError(response) {
|
|
36
|
+
let detail;
|
|
37
|
+
try {
|
|
38
|
+
const text = (await response.text()).slice(0, 500);
|
|
39
|
+
const parsed = JSON.parse(text);
|
|
40
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
41
|
+
const rec = parsed;
|
|
42
|
+
detail =
|
|
43
|
+
(typeof rec.message === 'string' && rec.message) || (typeof rec.error === 'string' && rec.error) || undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// non-JSON body: status alone is the contract
|
|
48
|
+
}
|
|
49
|
+
return new DevboxEnvdHttpError(response.status, `DevBox EnvD request failed with HTTP ${response.status}${detail ? `: ${detail}` : ''}`, detail);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Runs one command to completion (`/bin/bash -l -c <command>`) and collects
|
|
53
|
+
* stdout/stderr/exit code. The client aborts at timeoutMs; the abort surfaces
|
|
54
|
+
* with exitCode 124 (the hwexec async branch treats that as an uncertain start).
|
|
55
|
+
*/
|
|
56
|
+
export async function execDevboxOneShot(connection, command, timeoutMs) {
|
|
57
|
+
const payload = buildProcessStartRequest(command);
|
|
58
|
+
const body = encodeConnectFrame(payload);
|
|
59
|
+
const headers = {
|
|
60
|
+
...envdHeaders(connection),
|
|
61
|
+
'Connect-Protocol-Version': '1',
|
|
62
|
+
'Content-Type': 'application/connect+json',
|
|
63
|
+
'Connect-Timeout-Ms': String(Math.max(1, Math.round(timeoutMs))),
|
|
64
|
+
'Keepalive-Ping-Interval': '50',
|
|
65
|
+
};
|
|
66
|
+
const url = new URL(PROCESS_START_PATH, `${connection.envdUrl.replace(/\/$/, '')}/`).toString();
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
|
|
69
|
+
try {
|
|
70
|
+
let response;
|
|
71
|
+
try {
|
|
72
|
+
response = await devboxFetch(url, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers,
|
|
75
|
+
body: body,
|
|
76
|
+
signal: controller.signal,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (isAbort(error))
|
|
81
|
+
throw timeoutError(timeoutMs);
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
if (!response.ok)
|
|
85
|
+
throw await responseError(response);
|
|
86
|
+
assertConnectContentType(response.headers.get('content-type'));
|
|
87
|
+
if (!response.body)
|
|
88
|
+
throw new Error('DevBox EnvD returned an empty Connect stream.');
|
|
89
|
+
const reader = response.body.getReader();
|
|
90
|
+
const decoder = new ConnectFrameDecoder();
|
|
91
|
+
const stdoutDecoder = new TextDecoder('utf-8');
|
|
92
|
+
const stderrDecoder = new TextDecoder('utf-8');
|
|
93
|
+
const stdout = [];
|
|
94
|
+
const stderr = [];
|
|
95
|
+
let pid;
|
|
96
|
+
let exitCode;
|
|
97
|
+
let endError;
|
|
98
|
+
try {
|
|
99
|
+
for (;;) {
|
|
100
|
+
const { done, value } = await reader.read();
|
|
101
|
+
if (done)
|
|
102
|
+
break;
|
|
103
|
+
const fed = decoder.feed(value);
|
|
104
|
+
for (const eventPayload of fed.events) {
|
|
105
|
+
const event = parseProcessEvent(eventPayload);
|
|
106
|
+
if (event.pid !== undefined)
|
|
107
|
+
pid = event.pid;
|
|
108
|
+
const out = decodeProcessChunk(event.stdoutBase64);
|
|
109
|
+
if (out) {
|
|
110
|
+
const text = stdoutDecoder.decode(out, { stream: true });
|
|
111
|
+
if (text)
|
|
112
|
+
stdout.push(text);
|
|
113
|
+
}
|
|
114
|
+
const err = decodeProcessChunk(event.stderrBase64);
|
|
115
|
+
if (err) {
|
|
116
|
+
const text = stderrDecoder.decode(err, { stream: true });
|
|
117
|
+
if (text)
|
|
118
|
+
stderr.push(text);
|
|
119
|
+
}
|
|
120
|
+
if (event.exitCode !== undefined)
|
|
121
|
+
exitCode = event.exitCode;
|
|
122
|
+
}
|
|
123
|
+
if (fed.endError) {
|
|
124
|
+
endError = fed.endError;
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
decoder.finish();
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (isAbort(error))
|
|
132
|
+
throw timeoutError(timeoutMs);
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
try {
|
|
137
|
+
await reader.cancel();
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// stream may already be closed
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
stdout.push(stdoutDecoder.decode());
|
|
144
|
+
stderr.push(stderrDecoder.decode());
|
|
145
|
+
if (endError) {
|
|
146
|
+
throw new Error(`DevBox EnvD process failed (${endError.code}): ${endError.message}`);
|
|
147
|
+
}
|
|
148
|
+
if (exitCode === undefined) {
|
|
149
|
+
throw new Error('DevBox EnvD command stream ended without an exit status.');
|
|
150
|
+
}
|
|
151
|
+
return { stdout: stdout.join(''), stderr: stderr.join(''), exitCode, pid };
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function filesUrl(envdUrl, path) {
|
|
158
|
+
if (!path.startsWith('/'))
|
|
159
|
+
throw new Error('sandbox file path must be absolute.');
|
|
160
|
+
const url = new URL('/files', `${envdUrl.replace(/\/$/, '')}/`);
|
|
161
|
+
url.searchParams.set('path', path);
|
|
162
|
+
return url.toString();
|
|
163
|
+
}
|
|
164
|
+
export async function writeDevboxFile(connection, remotePath, data, timeoutMs = 120000) {
|
|
165
|
+
const response = await devboxFetch(filesUrl(connection.envdUrl, remotePath), {
|
|
166
|
+
method: 'POST',
|
|
167
|
+
headers: { ...envdHeaders(connection), 'Content-Type': 'application/octet-stream' },
|
|
168
|
+
body: data,
|
|
169
|
+
}, timeoutMs);
|
|
170
|
+
if (!response.ok)
|
|
171
|
+
throw await responseError(response);
|
|
172
|
+
await response.text();
|
|
173
|
+
}
|
|
174
|
+
export async function readDevboxFile(connection, remotePath, timeoutMs = 120000) {
|
|
175
|
+
const response = await devboxFetch(filesUrl(connection.envdUrl, remotePath), { method: 'GET', headers: envdHeaders(connection) }, timeoutMs);
|
|
176
|
+
if (!response.ok)
|
|
177
|
+
throw await responseError(response);
|
|
178
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
179
|
+
}
|
|
180
|
+
export async function statDevboxPath(connection, remotePath, timeoutMs = 30000) {
|
|
181
|
+
const url = new URL('/filesystem.Filesystem/Stat', `${connection.envdUrl.replace(/\/$/, '')}/`).toString();
|
|
182
|
+
const response = await devboxFetch(url, {
|
|
183
|
+
method: 'POST',
|
|
184
|
+
headers: {
|
|
185
|
+
...envdHeaders(connection),
|
|
186
|
+
'Connect-Protocol-Version': '1',
|
|
187
|
+
'Content-Type': 'application/json',
|
|
188
|
+
},
|
|
189
|
+
body: JSON.stringify({ path: remotePath }),
|
|
190
|
+
}, timeoutMs);
|
|
191
|
+
if (!response.ok)
|
|
192
|
+
throw await responseError(response);
|
|
193
|
+
const text = await response.text();
|
|
194
|
+
if (!text)
|
|
195
|
+
return undefined;
|
|
196
|
+
try {
|
|
197
|
+
const parsed = JSON.parse(text);
|
|
198
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
199
|
+
? parsed
|
|
200
|
+
: undefined;
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Client-side probe of the public app-port URL (no EnvD token needed).
|
|
208
|
+
* Used by deploy_check and expose_tunnel on the devbox backend.
|
|
209
|
+
*/
|
|
210
|
+
export async function probeDevboxAppUrl(envdUrl, port, timeoutMs = 10000) {
|
|
211
|
+
const url = devboxAppPortUrl(envdUrl, port);
|
|
212
|
+
try {
|
|
213
|
+
const response = await devboxFetch(url, { method: 'GET' }, timeoutMs);
|
|
214
|
+
return { url, status: response.status, ok: response.status >= 200 && response.status < 400 };
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return { url, status: 0, ok: false };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
export function devboxAppPortUrl(envdUrl, port) {
|
|
221
|
+
// The test pool advertises a devbox-test host that does not resolve publicly;
|
|
222
|
+
// the explicit DEVBOX_TEST_GATEWAY_HOST override makes the URL the developer
|
|
223
|
+
// receives actually reachable. Production (no override) returns it unchanged.
|
|
224
|
+
return rewriteDevboxUrl(deriveAppPortUrl(envdUrl, port));
|
|
225
|
+
}
|
|
226
|
+
/** Reads a whole local file as a Uint8Array (node:fs kept out of the wire module). */
|
|
227
|
+
export function bytesFromBuffer(buffer) {
|
|
228
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
229
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Pure DevBox EnvD wire contract (no I/O, no network): the ConnectRPC JSON
|
|
2
|
+
// frame codec for one-shot Process/Start plus the URL/header derivations.
|
|
3
|
+
// Pinned by test/devbox-envd-protocol.test.ts against the SDK-generated wire
|
|
4
|
+
// shapes verified in devbox-temp/TEST-FINDINGS.md.
|
|
5
|
+
import { Buffer } from 'node:buffer';
|
|
6
|
+
export const ENVD_API_PORT = 49983;
|
|
7
|
+
export const PROCESS_START_PATH = '/process.Process/Start';
|
|
8
|
+
export const CONNECT_CONTENT_TYPE = 'application/connect+json';
|
|
9
|
+
const FLAG_END_STREAM = 0x02;
|
|
10
|
+
const FLAG_COMPRESSED = 0x01;
|
|
11
|
+
/** One Connect envelope: 1 flag byte + 4-byte big-endian length + JSON body. */
|
|
12
|
+
export function encodeConnectFrame(value) {
|
|
13
|
+
const data = Buffer.from(JSON.stringify(value), 'utf8');
|
|
14
|
+
const frame = Buffer.allocUnsafe(5 + data.length);
|
|
15
|
+
frame.writeUInt8(0, 0);
|
|
16
|
+
frame.writeUInt32BE(data.length, 1);
|
|
17
|
+
data.copy(frame, 5);
|
|
18
|
+
return frame;
|
|
19
|
+
}
|
|
20
|
+
/** The exact body `Commands.run` sends: `/bin/bash -l -c <command>`, no PTY. */
|
|
21
|
+
export function buildProcessStartRequest(command, options = {}) {
|
|
22
|
+
if (!command || !command.trim()) {
|
|
23
|
+
throw new Error('sandbox exec: command must not be blank.');
|
|
24
|
+
}
|
|
25
|
+
const processBody = {
|
|
26
|
+
cmd: '/bin/bash',
|
|
27
|
+
args: ['-l', '-c', command],
|
|
28
|
+
envs: { ...(options.envs ?? {}) },
|
|
29
|
+
};
|
|
30
|
+
if (options.cwd)
|
|
31
|
+
processBody.cwd = options.cwd;
|
|
32
|
+
return { process: processBody, stdin: false };
|
|
33
|
+
}
|
|
34
|
+
function objectValue(value) {
|
|
35
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
36
|
+
}
|
|
37
|
+
export function decodeProcessChunk(base64) {
|
|
38
|
+
if (typeof base64 !== 'string')
|
|
39
|
+
return undefined;
|
|
40
|
+
// Strict shape validation mirrors the SDK: junk must not decode as binary.
|
|
41
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(base64)) {
|
|
42
|
+
throw new Error('DevBox EnvD returned invalid base64 process output.');
|
|
43
|
+
}
|
|
44
|
+
return Buffer.from(base64, 'base64');
|
|
45
|
+
}
|
|
46
|
+
export function parseProcessEvent(payload) {
|
|
47
|
+
const event = objectValue(payload.event);
|
|
48
|
+
if (!event)
|
|
49
|
+
return {};
|
|
50
|
+
const out = {};
|
|
51
|
+
const start = objectValue(event.start);
|
|
52
|
+
if (start && typeof start.pid === 'number' && Number.isSafeInteger(start.pid) && start.pid > 0) {
|
|
53
|
+
out.pid = start.pid;
|
|
54
|
+
}
|
|
55
|
+
const data = objectValue(event.data);
|
|
56
|
+
if (data) {
|
|
57
|
+
if (typeof data.stdout === 'string')
|
|
58
|
+
out.stdoutBase64 = data.stdout;
|
|
59
|
+
if (typeof data.stderr === 'string')
|
|
60
|
+
out.stderrBase64 = data.stderr;
|
|
61
|
+
}
|
|
62
|
+
const end = objectValue(event.end);
|
|
63
|
+
if (end) {
|
|
64
|
+
// EnvD omits exitCode on success (the platform sends
|
|
65
|
+
// {exited:true,status:"exited"}); the SDK's contract defaults it to 0.
|
|
66
|
+
const raw = end.exitCode ?? end.exit_code ?? 0;
|
|
67
|
+
const exitCode = Number(raw);
|
|
68
|
+
if (Number.isFinite(exitCode))
|
|
69
|
+
out.exitCode = exitCode;
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Incremental Connect stream decoder. Returns complete message payloads;
|
|
75
|
+
* the 0x02 end-stream frame carries an optional `{error:{code,message}}`.
|
|
76
|
+
*/
|
|
77
|
+
export class ConnectFrameDecoder {
|
|
78
|
+
buffer = Buffer.alloc(0);
|
|
79
|
+
ended = false;
|
|
80
|
+
feed(chunk) {
|
|
81
|
+
if (this.ended && chunk.length > 0) {
|
|
82
|
+
throw new Error('DevBox EnvD sent data after the Connect stream ended.');
|
|
83
|
+
}
|
|
84
|
+
this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk)]);
|
|
85
|
+
const events = [];
|
|
86
|
+
let endError;
|
|
87
|
+
while (this.buffer.length >= 5) {
|
|
88
|
+
const flags = this.buffer.readUInt8(0);
|
|
89
|
+
const size = this.buffer.readUInt32BE(1);
|
|
90
|
+
if (this.buffer.length < size + 5)
|
|
91
|
+
break;
|
|
92
|
+
const body = this.buffer.subarray(5, size + 5);
|
|
93
|
+
this.buffer = this.buffer.subarray(size + 5);
|
|
94
|
+
if ((flags & FLAG_COMPRESSED) !== 0) {
|
|
95
|
+
throw new Error('DevBox EnvD returned a compressed Connect message (not supported).');
|
|
96
|
+
}
|
|
97
|
+
let payload = {};
|
|
98
|
+
if (body.length > 0) {
|
|
99
|
+
try {
|
|
100
|
+
const parsed = JSON.parse(body.toString('utf8'));
|
|
101
|
+
payload = objectValue(parsed) ?? {};
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new Error('DevBox EnvD returned invalid Connect JSON.');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if ((flags & FLAG_END_STREAM) !== 0) {
|
|
108
|
+
this.ended = true;
|
|
109
|
+
const error = objectValue(payload.error);
|
|
110
|
+
if (error) {
|
|
111
|
+
endError = {
|
|
112
|
+
code: typeof error.code === 'string' ? error.code : 'unknown',
|
|
113
|
+
message: typeof error.message === 'string' ? error.message : 'EnvD request failed',
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (this.buffer.length > 0) {
|
|
117
|
+
throw new Error('DevBox EnvD sent data after the Connect stream ended.');
|
|
118
|
+
}
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
events.push(payload);
|
|
122
|
+
}
|
|
123
|
+
return { events, endError, ended: this.ended };
|
|
124
|
+
}
|
|
125
|
+
finish() {
|
|
126
|
+
if (this.buffer.length > 0) {
|
|
127
|
+
throw new Error('DevBox EnvD returned a truncated Connect stream.');
|
|
128
|
+
}
|
|
129
|
+
if (!this.ended) {
|
|
130
|
+
throw new Error('DevBox EnvD closed the Connect stream without a trailer.');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
export function assertConnectContentType(contentType) {
|
|
135
|
+
const base = (contentType ?? '').split(';', 1)[0]?.trim().toLowerCase();
|
|
136
|
+
if (base !== CONNECT_CONTENT_TYPE) {
|
|
137
|
+
throw new Error(`DevBox EnvD returned an invalid content type (${contentType ?? 'missing'}).`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** EnvD host names embed the API port: `<tunnel>-49983.domain` -> `<tunnel>-<port>.domain`. */
|
|
141
|
+
export function deriveAppPortUrl(envdUrl, port) {
|
|
142
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
|
|
143
|
+
throw new Error(`sandbox preview: invalid app port ${port}.`);
|
|
144
|
+
}
|
|
145
|
+
const url = new URL(envdUrl);
|
|
146
|
+
url.hostname = url.hostname.replace(/-49983(?=\.|$)/, `-${port}`);
|
|
147
|
+
url.pathname = '/';
|
|
148
|
+
url.search = '';
|
|
149
|
+
url.hash = '';
|
|
150
|
+
return url.toString();
|
|
151
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// The ONLY devbox module allowed to touch undici. The normal path rides
|
|
2
|
+
// fetchWithProxy (system proxy posture); the test-only TLS/DNS switches build
|
|
3
|
+
// a dedicated undici Agent. Production defaults stay strict TLS + real DNS.
|
|
4
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
5
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
6
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
7
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
return path;
|
|
11
|
+
};
|
|
12
|
+
import { fetchWithProxy } from "../../proxy/proxy-agent.js";
|
|
13
|
+
import { isDevboxBackend } from "./devbox-backend.js";
|
|
14
|
+
let testDispatcher;
|
|
15
|
+
let testDispatcherKey = '';
|
|
16
|
+
let insecureWarningEmitted = false;
|
|
17
|
+
function testOverridesActive() {
|
|
18
|
+
if (!isDevboxBackend())
|
|
19
|
+
return false;
|
|
20
|
+
return (process.env.DEVBOX_TLS_INSECURE === '1' ||
|
|
21
|
+
Boolean(process.env.DEVBOX_TEST_GATEWAY_HOST) ||
|
|
22
|
+
Boolean(process.env.DEVBOX_TEST_GATEWAY_IP));
|
|
23
|
+
}
|
|
24
|
+
const NODE_UNDICI_SPECIFIER = 'node:undici';
|
|
25
|
+
async function importUndici() {
|
|
26
|
+
try {
|
|
27
|
+
// Node exposes the bundled client as `node:undici`; fall back to the npm package.
|
|
28
|
+
return (await import(__rewriteRelativeImportExtension(NODE_UNDICI_SPECIFIER)));
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return await import('undici');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Test gateway rewrite (explicit env only): the test pool advertises a
|
|
36
|
+
* `devbox-test.hwtunnel.com` host that does not resolve publicly; keep the
|
|
37
|
+
* tunnel-id label and swap the gateway suffix.
|
|
38
|
+
*/
|
|
39
|
+
export function rewriteDevboxUrl(raw) {
|
|
40
|
+
const testHost = process.env.DEVBOX_TEST_GATEWAY_HOST;
|
|
41
|
+
if (!testOverridesActive() || !testHost)
|
|
42
|
+
return raw;
|
|
43
|
+
let url;
|
|
44
|
+
try {
|
|
45
|
+
url = new URL(raw);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return raw;
|
|
49
|
+
}
|
|
50
|
+
if (url.hostname.endsWith(`.${testHost}`) || url.hostname === testHost)
|
|
51
|
+
return raw;
|
|
52
|
+
const label = url.hostname.split('.')[0];
|
|
53
|
+
if (label)
|
|
54
|
+
url.hostname = `${label}.${testHost}`;
|
|
55
|
+
return url.toString();
|
|
56
|
+
}
|
|
57
|
+
async function getTestDispatcher() {
|
|
58
|
+
if (!testOverridesActive())
|
|
59
|
+
return undefined;
|
|
60
|
+
const tlsInsecure = process.env.DEVBOX_TLS_INSECURE === '1';
|
|
61
|
+
const testHost = process.env.DEVBOX_TEST_GATEWAY_HOST ?? '';
|
|
62
|
+
const testIp = process.env.DEVBOX_TEST_GATEWAY_IP ?? '';
|
|
63
|
+
const key = `${tlsInsecure ? '1' : '0'}|${testHost}|${testIp}`;
|
|
64
|
+
if (testDispatcher && testDispatcherKey === key)
|
|
65
|
+
return testDispatcher;
|
|
66
|
+
const { Agent } = await importUndici();
|
|
67
|
+
const connectOptions = { rejectUnauthorized: !tlsInsecure };
|
|
68
|
+
if (testIp) {
|
|
69
|
+
const dns = await import('node:dns');
|
|
70
|
+
connectOptions.lookup = (hostname, options, callback) => {
|
|
71
|
+
const wantsAll = typeof options === 'object' && options !== null && options.all === true;
|
|
72
|
+
if (testHost && hostname.endsWith(`.${testHost}`)) {
|
|
73
|
+
if (wantsAll)
|
|
74
|
+
return callback(null, [{ address: testIp, family: 4 }]);
|
|
75
|
+
return callback(null, testIp, 4);
|
|
76
|
+
}
|
|
77
|
+
return dns.lookup(hostname, options, callback);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
testDispatcher = new Agent({ connect: connectOptions });
|
|
81
|
+
testDispatcherKey = key;
|
|
82
|
+
if (!insecureWarningEmitted && (tlsInsecure || testHost || testIp)) {
|
|
83
|
+
insecureWarningEmitted = true;
|
|
84
|
+
console.warn('[devbox] TEST-only transport overrides active (DEVBOX_TLS_INSECURE / DEVBOX_TEST_GATEWAY_*). ' +
|
|
85
|
+
'Never set these in production.');
|
|
86
|
+
}
|
|
87
|
+
return testDispatcher;
|
|
88
|
+
}
|
|
89
|
+
/** DevBox data/API fetch: proxy-aware in production, explicit test Agent otherwise. */
|
|
90
|
+
export async function devboxFetch(url, init = {}, timeoutMs) {
|
|
91
|
+
const rewritten = rewriteDevboxUrl(url);
|
|
92
|
+
const signal = timeoutMs !== undefined
|
|
93
|
+
? init.signal
|
|
94
|
+
? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)])
|
|
95
|
+
: AbortSignal.timeout(timeoutMs)
|
|
96
|
+
: init.signal;
|
|
97
|
+
const merged = signal ? { ...init, signal } : init;
|
|
98
|
+
const dispatcher = await getTestDispatcher();
|
|
99
|
+
if (!dispatcher) {
|
|
100
|
+
return (await fetchWithProxy(rewritten, merged));
|
|
101
|
+
}
|
|
102
|
+
const { fetch: undiciFetch } = await importUndici();
|
|
103
|
+
const response = await undiciFetch(rewritten, {
|
|
104
|
+
...merged,
|
|
105
|
+
dispatcher,
|
|
106
|
+
});
|
|
107
|
+
return response;
|
|
108
|
+
}
|
|
109
|
+
export async function closeDevboxTestDispatcher() {
|
|
110
|
+
if (testDispatcher) {
|
|
111
|
+
try {
|
|
112
|
+
await testDispatcher.close();
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// best-effort test cleanup
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
testDispatcher = undefined;
|
|
119
|
+
testDispatcherKey = '';
|
|
120
|
+
insecureWarningEmitted = false;
|
|
121
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// DevBox control plane over hdkitservice (`/sandbox/devbox/*`). Every call
|
|
2
|
+
// carries the user's AK/SK (+ optional X-HW-Security-Token) through the one
|
|
3
|
+
// shared hdkitRequest seam — there is no sandbox key. EnvD tokens returned by
|
|
4
|
+
// connect/refresh stay in the in-process connection cache only.
|
|
5
|
+
import { asRecord } from "../../lib/as-record.js";
|
|
6
|
+
import { hdkitRequest } from "../../lib/hdkit/hdkitservice-api.js";
|
|
7
|
+
import { requireDevboxConnection, devboxTokenNeedsRefresh, setDevboxConnectionFromResponse, } from "./devbox-connections.js";
|
|
8
|
+
export const DEVBOX_CONNECT_TIMEOUT_DEFAULT = 1800;
|
|
9
|
+
const DEVBOX_CONNECT_TIMEOUT_MIN = 10;
|
|
10
|
+
const DEVBOX_CONNECT_TIMEOUT_MAX = 86400;
|
|
11
|
+
export function devboxConnectTimeoutSeconds() {
|
|
12
|
+
const raw = process.env.HW_SANDBOX_CONNECT_TIMEOUT_SECONDS;
|
|
13
|
+
if (raw === undefined || raw === '')
|
|
14
|
+
return DEVBOX_CONNECT_TIMEOUT_DEFAULT;
|
|
15
|
+
const value = Number(raw);
|
|
16
|
+
if (!Number.isSafeInteger(value) || value < DEVBOX_CONNECT_TIMEOUT_MIN || value > DEVBOX_CONNECT_TIMEOUT_MAX) {
|
|
17
|
+
throw new Error(`HW_SANDBOX_CONNECT_TIMEOUT_SECONDS must be an integer between ${DEVBOX_CONNECT_TIMEOUT_MIN} and ` +
|
|
18
|
+
`${DEVBOX_CONNECT_TIMEOUT_MAX} (got "${raw}").`);
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
export async function devboxConnect(options = {}) {
|
|
23
|
+
const body = {
|
|
24
|
+
timeout: options.timeoutSeconds ?? devboxConnectTimeoutSeconds(),
|
|
25
|
+
source: options.source || 'CLI',
|
|
26
|
+
};
|
|
27
|
+
if (options.envVars && Object.keys(options.envVars).length > 0)
|
|
28
|
+
body.envVars = options.envVars;
|
|
29
|
+
if (options.poolType)
|
|
30
|
+
body.pool_type = options.poolType;
|
|
31
|
+
return asRecord(await hdkitRequest('POST', 'sandbox/devbox/connect', body, 300000));
|
|
32
|
+
}
|
|
33
|
+
export async function devboxRefresh(sandboxId, timeoutSeconds) {
|
|
34
|
+
const body = {
|
|
35
|
+
timeout: timeoutSeconds ?? devboxConnectTimeoutSeconds(),
|
|
36
|
+
};
|
|
37
|
+
return asRecord(await hdkitRequest('POST', `sandbox/devbox/${encodeURIComponent(sandboxId)}/connect`, body, 120000));
|
|
38
|
+
}
|
|
39
|
+
export async function devboxShutdown(sandboxId) {
|
|
40
|
+
return asRecord(await hdkitRequest('POST', `sandbox/devbox/${encodeURIComponent(sandboxId)}/shutdown`, {}, 120000));
|
|
41
|
+
}
|
|
42
|
+
export async function devboxKill(sandboxId) {
|
|
43
|
+
return asRecord(await hdkitRequest('DELETE', `sandbox/devbox/${encodeURIComponent(sandboxId)}`, undefined, 120000));
|
|
44
|
+
}
|
|
45
|
+
export async function devboxStatus(sandboxId) {
|
|
46
|
+
return asRecord(await hdkitRequest('GET', `sandbox/devbox/${encodeURIComponent(sandboxId)}`, undefined, 30000));
|
|
47
|
+
}
|
|
48
|
+
/** True for EnvD 401/403 — triggers the one automatic refresh+retry. */
|
|
49
|
+
export function isDevboxAuthError(error) {
|
|
50
|
+
if (!error || typeof error !== 'object')
|
|
51
|
+
return false;
|
|
52
|
+
const rec = error;
|
|
53
|
+
return rec.auth === true || rec.status === 401 || rec.status === 403;
|
|
54
|
+
}
|
|
55
|
+
/** Calls hdkitservice refresh with the current AK/SK and updates the cache. */
|
|
56
|
+
export async function refreshDevboxConnection(connection) {
|
|
57
|
+
const result = await devboxRefresh(connection.sandboxId);
|
|
58
|
+
return setDevboxConnectionFromResponse(connection.workspaceId, result);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Data-plane wrapper: refresh the EnvD token five minutes before expiry, and
|
|
62
|
+
* on a 401/403 refresh once and retry the same operation. A second auth
|
|
63
|
+
* failure is returned to the caller (control-plane re-authentication is the
|
|
64
|
+
* agent's next action).
|
|
65
|
+
*/
|
|
66
|
+
export async function withDevboxConnection(workspaceId, operation) {
|
|
67
|
+
let connection = requireDevboxConnection(workspaceId);
|
|
68
|
+
if (devboxTokenNeedsRefresh(connection)) {
|
|
69
|
+
connection = await refreshDevboxConnection(connection);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return await operation(connection);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (!isDevboxAuthError(error))
|
|
76
|
+
throw error;
|
|
77
|
+
const refreshed = await refreshDevboxConnection(requireDevboxConnection(workspaceId));
|
|
78
|
+
return await operation(refreshed);
|
|
79
|
+
}
|
|
80
|
+
}
|