disk 1.14.0 → 1.15.0
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 +149 -37
- package/dist/{archil-DaIWdn2s.d.cts → archil-CenIy1WD.d.mts} +86 -2
- package/dist/{archil-DbdoAk0f.d.mts → archil-DHPfg1b9.d.cts} +86 -2
- package/dist/archil-cli.mjs +591 -0
- package/dist/cli.mjs +6 -275
- package/dist/disk-command-CvRVHqnG.mjs +285 -0
- package/dist/index.cjs +21 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +3 -2
- package/dist/internal/tools.d.cts +1 -1
- package/dist/internal/tools.d.mts +1 -1
- package/dist/node/index.cjs +21 -1
- package/dist/node/index.mjs +14 -2
- package/dist/node/sandbox-desktop-CrvuoiGi.mjs +150 -0
- package/dist/node/sandbox-desktop-DBs8jhKW.cjs +197 -0
- package/dist/node/tunnel.cjs +253 -0
- package/dist/node/tunnel.mjs +248 -0
- package/dist/sandbox-cli.mjs +4 -496
- package/dist/sandbox-command-DJZqMVHm.mjs +1073 -0
- package/dist/sandbox-desktop-CrvuoiGi.mjs +150 -0
- package/dist/sandbox-desktop-DBs8jhKW.cjs +197 -0
- package/dist/{sandbox-options-trHjQs_f.mjs → sandbox-options-AO9jKF4-.mjs} +182 -9
- package/dist/{src-DGB_iQTG.mjs → src-BFPiWUCL.mjs} +13 -1
- package/dist/tunnel.cjs +253 -0
- package/dist/tunnel.d.cts +77 -0
- package/dist/tunnel.d.mts +77 -0
- package/dist/tunnel.mjs +248 -0
- package/package.json +12 -2
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_sandbox_desktop = require("./sandbox-desktop-DBs8jhKW.cjs");
|
|
3
|
+
let node_net = require("node:net");
|
|
4
|
+
let node_tls = require("node:tls");
|
|
5
|
+
//#region src/tunnel.ts
|
|
6
|
+
const PORT_TOKEN_HEADER = "X-Archil-Token";
|
|
7
|
+
const MAX_REQUEST_HEAD_BYTES = 16 * 1024;
|
|
8
|
+
const HEAD_END = Buffer.from("\r\n\r\n");
|
|
9
|
+
const UPGRADE = /^upgrade:\s*websocket\s*$/im;
|
|
10
|
+
async function openPortTunnel(options) {
|
|
11
|
+
const connectUpstream = options.connectUpstream ?? ((hostname) => (0, node_tls.connect)({
|
|
12
|
+
host: hostname,
|
|
13
|
+
port: 443,
|
|
14
|
+
servername: hostname
|
|
15
|
+
}));
|
|
16
|
+
let portToken = options.portToken;
|
|
17
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
18
|
+
const websockets = /* @__PURE__ */ new Set();
|
|
19
|
+
const report = () => options.onActivity?.({
|
|
20
|
+
connections: sockets.size,
|
|
21
|
+
websockets: websockets.size
|
|
22
|
+
});
|
|
23
|
+
const server = (0, node_net.createServer)((client) => {
|
|
24
|
+
sockets.add(client);
|
|
25
|
+
report();
|
|
26
|
+
client.once("close", () => {
|
|
27
|
+
sockets.delete(client);
|
|
28
|
+
websockets.delete(client);
|
|
29
|
+
report();
|
|
30
|
+
});
|
|
31
|
+
relay(client, () => connectUpstream(options.hostname), portToken, () => server.address().port, (head) => {
|
|
32
|
+
if (UPGRADE.test(head.toString("latin1"))) {
|
|
33
|
+
websockets.add(client);
|
|
34
|
+
report();
|
|
35
|
+
}
|
|
36
|
+
}).catch(() => client.destroy());
|
|
37
|
+
});
|
|
38
|
+
await listen(server, options.localPort);
|
|
39
|
+
return {
|
|
40
|
+
port: server.address().port,
|
|
41
|
+
setPortToken: (token) => {
|
|
42
|
+
portToken = token;
|
|
43
|
+
},
|
|
44
|
+
close: () => new Promise((resolve) => {
|
|
45
|
+
for (const socket of sockets) socket.destroy();
|
|
46
|
+
server.close(() => resolve());
|
|
47
|
+
})
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async function relay(client, connectUpstream, portToken, localPort, onHead) {
|
|
51
|
+
const head = await readRequestHead(client);
|
|
52
|
+
if (!isLocalHost(requestHost(head), localPort())) {
|
|
53
|
+
const body = "This tunnel only serves requests to localhost.\n";
|
|
54
|
+
client.end(`HTTP/1.1 421 Misdirected Request\r\nContent-Type: text/plain\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
onHead(head);
|
|
58
|
+
const upstream = connectUpstream();
|
|
59
|
+
upstream.on("error", () => client.destroy());
|
|
60
|
+
client.on("error", () => upstream.destroy());
|
|
61
|
+
upstream.on("close", () => client.destroy());
|
|
62
|
+
client.on("close", () => upstream.destroy());
|
|
63
|
+
upstream.write(addRequestHeader(head, `${PORT_TOKEN_HEADER}: ${portToken}`));
|
|
64
|
+
client.pipe(upstream).pipe(client);
|
|
65
|
+
}
|
|
66
|
+
function requestHost(head) {
|
|
67
|
+
return /^host:[ \t]*([^\r\n]*?)[ \t]*$/im.exec(head.toString("latin1"))?.[1]?.toLowerCase();
|
|
68
|
+
}
|
|
69
|
+
/** Whether `host` (a Host header) names this machine's loopback on `port`. */
|
|
70
|
+
function isLocalHost(host, port) {
|
|
71
|
+
if (!host) return false;
|
|
72
|
+
return [
|
|
73
|
+
"127.0.0.1",
|
|
74
|
+
"localhost",
|
|
75
|
+
"[::1]"
|
|
76
|
+
].some((name) => host === `${name}:${port}` || port === 80 && host === name);
|
|
77
|
+
}
|
|
78
|
+
/** Inserts `header` after the request line of the buffered request head. */
|
|
79
|
+
function addRequestHeader(head, header) {
|
|
80
|
+
const requestLineEnd = head.indexOf("\r\n") + 2;
|
|
81
|
+
return Buffer.concat([
|
|
82
|
+
head.subarray(0, requestLineEnd),
|
|
83
|
+
Buffer.from(`${header}\r\n`),
|
|
84
|
+
head.subarray(requestLineEnd)
|
|
85
|
+
]);
|
|
86
|
+
}
|
|
87
|
+
/** Reads through the end of the first request's headers; returns everything read. */
|
|
88
|
+
function readRequestHead(client) {
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
let buffered = Buffer.alloc(0);
|
|
91
|
+
const cleanup = () => {
|
|
92
|
+
client.off("data", onData);
|
|
93
|
+
client.off("end", onEnd);
|
|
94
|
+
client.off("error", onEnd);
|
|
95
|
+
};
|
|
96
|
+
const onData = (chunk) => {
|
|
97
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
98
|
+
if (buffered.includes(HEAD_END)) {
|
|
99
|
+
cleanup();
|
|
100
|
+
client.pause();
|
|
101
|
+
resolve(buffered);
|
|
102
|
+
} else if (buffered.length > MAX_REQUEST_HEAD_BYTES) {
|
|
103
|
+
cleanup();
|
|
104
|
+
reject(/* @__PURE__ */ new Error("request head too large"));
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const onEnd = () => {
|
|
108
|
+
cleanup();
|
|
109
|
+
reject(/* @__PURE__ */ new Error("connection closed before the request head"));
|
|
110
|
+
};
|
|
111
|
+
client.on("data", onData);
|
|
112
|
+
client.on("end", onEnd);
|
|
113
|
+
client.on("error", onEnd);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
function listen(server, port) {
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
server.once("error", reject);
|
|
119
|
+
server.listen(port, "127.0.0.1", () => {
|
|
120
|
+
server.off("error", reject);
|
|
121
|
+
resolve();
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
const TOKEN_TTL = "12h";
|
|
126
|
+
/** Renew two hours before the 12-hour TTL, leaving room for retries. */
|
|
127
|
+
const TOKEN_RENEW_AFTER_MS = 600 * 60 * 1e3;
|
|
128
|
+
const TOKEN_RENEW_CHECK_MS = 30 * 1e3;
|
|
129
|
+
const KEEPALIVE_RETRY_MS = 5 * 1e3;
|
|
130
|
+
/** The keepalive ends on its own after this, in case the process dies without cleaning up. */
|
|
131
|
+
const KEEPALIVE_MAX_SECONDS = 2160 * 60;
|
|
132
|
+
/**
|
|
133
|
+
* Serves `port` of a running sandbox on localhost without making it public,
|
|
134
|
+
* until {@link ForwardedPort.close}. The access token is renewed before it
|
|
135
|
+
* expires.
|
|
136
|
+
*/
|
|
137
|
+
async function forwardPort(sandbox, port, options = {}) {
|
|
138
|
+
const warn = options.onWarning ?? (() => {});
|
|
139
|
+
const open = options.openTunnel ?? openPortTunnel;
|
|
140
|
+
let access = await sandbox.createPortToken(port, { ttl: TOKEN_TTL });
|
|
141
|
+
const tunnelOptions = (localPort) => ({
|
|
142
|
+
hostname: access.hostname,
|
|
143
|
+
portToken: access.token,
|
|
144
|
+
localPort,
|
|
145
|
+
onActivity: options.onActivity
|
|
146
|
+
});
|
|
147
|
+
let tunnel;
|
|
148
|
+
try {
|
|
149
|
+
tunnel = await open(tunnelOptions(options.localPort ?? port)).catch((error) => {
|
|
150
|
+
if (options.localPort !== void 0 || error.code !== "EADDRINUSE" && error.code !== "EACCES") throw error;
|
|
151
|
+
return open(tunnelOptions(0));
|
|
152
|
+
});
|
|
153
|
+
} catch (error) {
|
|
154
|
+
await sandbox.deletePortToken(access.id).catch(() => {});
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
let closing = false;
|
|
158
|
+
let wakeSleeper;
|
|
159
|
+
const pause = (ms) => new Promise((resolve) => {
|
|
160
|
+
const timer = setTimeout(resolve, ms);
|
|
161
|
+
timer.unref?.();
|
|
162
|
+
wakeSleeper = () => {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
resolve();
|
|
165
|
+
};
|
|
166
|
+
});
|
|
167
|
+
let keepalive;
|
|
168
|
+
const keepAwake = options.keepAwake === false ? void 0 : (async () => {
|
|
169
|
+
let failures = 0;
|
|
170
|
+
while (!closing) {
|
|
171
|
+
try {
|
|
172
|
+
const started = await sandbox.run("exec tail -f /dev/null", {
|
|
173
|
+
collectOutput: false,
|
|
174
|
+
timeoutSeconds: KEEPALIVE_MAX_SECONDS
|
|
175
|
+
});
|
|
176
|
+
if (closing) {
|
|
177
|
+
await started.kill().catch(() => {});
|
|
178
|
+
await started.disconnect().catch(() => {});
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
keepalive = started;
|
|
182
|
+
if (failures > 0) warn("The sandbox is being kept awake again.");
|
|
183
|
+
failures = 0;
|
|
184
|
+
await keepalive.wait();
|
|
185
|
+
} catch {}
|
|
186
|
+
if (closing) break;
|
|
187
|
+
if (failures++ === 0) warn("Lost the connection keeping the sandbox awake; retrying. It may pause after its idle timeout until then.");
|
|
188
|
+
await pause(Math.min(KEEPALIVE_RETRY_MS * failures, 6e4));
|
|
189
|
+
}
|
|
190
|
+
})();
|
|
191
|
+
let renewAt = Date.now() + TOKEN_RENEW_AFTER_MS;
|
|
192
|
+
let renewFailures = 0;
|
|
193
|
+
let renewing;
|
|
194
|
+
const renew = () => {
|
|
195
|
+
renewing = (async () => {
|
|
196
|
+
const next = await sandbox.createPortToken(port, { ttl: TOKEN_TTL });
|
|
197
|
+
if (closing) {
|
|
198
|
+
await sandbox.deletePortToken(next.id).catch(() => {});
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
tunnel.setPortToken(next.token);
|
|
202
|
+
const previous = access;
|
|
203
|
+
access = next;
|
|
204
|
+
renewAt = Date.now() + TOKEN_RENEW_AFTER_MS;
|
|
205
|
+
if (renewFailures > 0) warn("Renewed the tunnel's access token.");
|
|
206
|
+
renewFailures = 0;
|
|
207
|
+
await sandbox.deletePortToken(previous.id).catch(() => {});
|
|
208
|
+
})().catch(() => {
|
|
209
|
+
if (renewFailures++ === 0) warn("Couldn't renew the tunnel's access token; retrying. New connections fail if it expires first.");
|
|
210
|
+
renewAt = Date.now() + Math.min(6e4 * renewFailures, 10 * 6e4);
|
|
211
|
+
}).finally(() => {
|
|
212
|
+
renewing = void 0;
|
|
213
|
+
});
|
|
214
|
+
};
|
|
215
|
+
const renewal = setInterval(() => {
|
|
216
|
+
if (!renewing && !closing && Date.now() >= renewAt) renew();
|
|
217
|
+
}, TOKEN_RENEW_CHECK_MS);
|
|
218
|
+
renewal.unref?.();
|
|
219
|
+
let closed;
|
|
220
|
+
return {
|
|
221
|
+
localPort: tunnel.port,
|
|
222
|
+
url: `http://127.0.0.1:${tunnel.port}`,
|
|
223
|
+
close: () => closed ??= (async () => {
|
|
224
|
+
clearInterval(renewal);
|
|
225
|
+
closing = true;
|
|
226
|
+
wakeSleeper?.();
|
|
227
|
+
await renewing;
|
|
228
|
+
await tunnel.close();
|
|
229
|
+
await keepalive?.kill().catch(() => {});
|
|
230
|
+
await keepalive?.disconnect().catch(() => {});
|
|
231
|
+
await keepAwake;
|
|
232
|
+
await sandbox.deletePortToken(access.id).catch(() => {});
|
|
233
|
+
})()
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Starts a sandbox's desktop and serves it on 127.0.0.1 (port 6080 unless
|
|
238
|
+
* taken). Open `viewerUrl` in a browser on this machine.
|
|
239
|
+
*/
|
|
240
|
+
async function openDesktopTunnel(sandbox, options = {}) {
|
|
241
|
+
const { token } = await sandbox.desktop.start();
|
|
242
|
+
const forwarded = await forwardPort(sandbox, require_sandbox_desktop.DESKTOP_PORT, options);
|
|
243
|
+
return {
|
|
244
|
+
...forwarded,
|
|
245
|
+
viewerUrl: `${forwarded.url}${require_sandbox_desktop.desktopViewerPath(token)}`
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
//#endregion
|
|
249
|
+
exports.addRequestHeader = addRequestHeader;
|
|
250
|
+
exports.forwardPort = forwardPort;
|
|
251
|
+
exports.isLocalHost = isLocalHost;
|
|
252
|
+
exports.openDesktopTunnel = openDesktopTunnel;
|
|
253
|
+
exports.openPortTunnel = openPortTunnel;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { c as desktopViewerPath, i as DESKTOP_PORT } from "./sandbox-desktop-CrvuoiGi.mjs";
|
|
2
|
+
import { createServer } from "node:net";
|
|
3
|
+
import { connect } from "node:tls";
|
|
4
|
+
//#region src/tunnel.ts
|
|
5
|
+
const PORT_TOKEN_HEADER = "X-Archil-Token";
|
|
6
|
+
const MAX_REQUEST_HEAD_BYTES = 16 * 1024;
|
|
7
|
+
const HEAD_END = Buffer.from("\r\n\r\n");
|
|
8
|
+
const UPGRADE = /^upgrade:\s*websocket\s*$/im;
|
|
9
|
+
async function openPortTunnel(options) {
|
|
10
|
+
const connectUpstream = options.connectUpstream ?? ((hostname) => connect({
|
|
11
|
+
host: hostname,
|
|
12
|
+
port: 443,
|
|
13
|
+
servername: hostname
|
|
14
|
+
}));
|
|
15
|
+
let portToken = options.portToken;
|
|
16
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
17
|
+
const websockets = /* @__PURE__ */ new Set();
|
|
18
|
+
const report = () => options.onActivity?.({
|
|
19
|
+
connections: sockets.size,
|
|
20
|
+
websockets: websockets.size
|
|
21
|
+
});
|
|
22
|
+
const server = createServer((client) => {
|
|
23
|
+
sockets.add(client);
|
|
24
|
+
report();
|
|
25
|
+
client.once("close", () => {
|
|
26
|
+
sockets.delete(client);
|
|
27
|
+
websockets.delete(client);
|
|
28
|
+
report();
|
|
29
|
+
});
|
|
30
|
+
relay(client, () => connectUpstream(options.hostname), portToken, () => server.address().port, (head) => {
|
|
31
|
+
if (UPGRADE.test(head.toString("latin1"))) {
|
|
32
|
+
websockets.add(client);
|
|
33
|
+
report();
|
|
34
|
+
}
|
|
35
|
+
}).catch(() => client.destroy());
|
|
36
|
+
});
|
|
37
|
+
await listen(server, options.localPort);
|
|
38
|
+
return {
|
|
39
|
+
port: server.address().port,
|
|
40
|
+
setPortToken: (token) => {
|
|
41
|
+
portToken = token;
|
|
42
|
+
},
|
|
43
|
+
close: () => new Promise((resolve) => {
|
|
44
|
+
for (const socket of sockets) socket.destroy();
|
|
45
|
+
server.close(() => resolve());
|
|
46
|
+
})
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
async function relay(client, connectUpstream, portToken, localPort, onHead) {
|
|
50
|
+
const head = await readRequestHead(client);
|
|
51
|
+
if (!isLocalHost(requestHost(head), localPort())) {
|
|
52
|
+
const body = "This tunnel only serves requests to localhost.\n";
|
|
53
|
+
client.end(`HTTP/1.1 421 Misdirected Request\r\nContent-Type: text/plain\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
onHead(head);
|
|
57
|
+
const upstream = connectUpstream();
|
|
58
|
+
upstream.on("error", () => client.destroy());
|
|
59
|
+
client.on("error", () => upstream.destroy());
|
|
60
|
+
upstream.on("close", () => client.destroy());
|
|
61
|
+
client.on("close", () => upstream.destroy());
|
|
62
|
+
upstream.write(addRequestHeader(head, `${PORT_TOKEN_HEADER}: ${portToken}`));
|
|
63
|
+
client.pipe(upstream).pipe(client);
|
|
64
|
+
}
|
|
65
|
+
function requestHost(head) {
|
|
66
|
+
return /^host:[ \t]*([^\r\n]*?)[ \t]*$/im.exec(head.toString("latin1"))?.[1]?.toLowerCase();
|
|
67
|
+
}
|
|
68
|
+
/** Whether `host` (a Host header) names this machine's loopback on `port`. */
|
|
69
|
+
function isLocalHost(host, port) {
|
|
70
|
+
if (!host) return false;
|
|
71
|
+
return [
|
|
72
|
+
"127.0.0.1",
|
|
73
|
+
"localhost",
|
|
74
|
+
"[::1]"
|
|
75
|
+
].some((name) => host === `${name}:${port}` || port === 80 && host === name);
|
|
76
|
+
}
|
|
77
|
+
/** Inserts `header` after the request line of the buffered request head. */
|
|
78
|
+
function addRequestHeader(head, header) {
|
|
79
|
+
const requestLineEnd = head.indexOf("\r\n") + 2;
|
|
80
|
+
return Buffer.concat([
|
|
81
|
+
head.subarray(0, requestLineEnd),
|
|
82
|
+
Buffer.from(`${header}\r\n`),
|
|
83
|
+
head.subarray(requestLineEnd)
|
|
84
|
+
]);
|
|
85
|
+
}
|
|
86
|
+
/** Reads through the end of the first request's headers; returns everything read. */
|
|
87
|
+
function readRequestHead(client) {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
let buffered = Buffer.alloc(0);
|
|
90
|
+
const cleanup = () => {
|
|
91
|
+
client.off("data", onData);
|
|
92
|
+
client.off("end", onEnd);
|
|
93
|
+
client.off("error", onEnd);
|
|
94
|
+
};
|
|
95
|
+
const onData = (chunk) => {
|
|
96
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
97
|
+
if (buffered.includes(HEAD_END)) {
|
|
98
|
+
cleanup();
|
|
99
|
+
client.pause();
|
|
100
|
+
resolve(buffered);
|
|
101
|
+
} else if (buffered.length > MAX_REQUEST_HEAD_BYTES) {
|
|
102
|
+
cleanup();
|
|
103
|
+
reject(/* @__PURE__ */ new Error("request head too large"));
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const onEnd = () => {
|
|
107
|
+
cleanup();
|
|
108
|
+
reject(/* @__PURE__ */ new Error("connection closed before the request head"));
|
|
109
|
+
};
|
|
110
|
+
client.on("data", onData);
|
|
111
|
+
client.on("end", onEnd);
|
|
112
|
+
client.on("error", onEnd);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
function listen(server, port) {
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
server.once("error", reject);
|
|
118
|
+
server.listen(port, "127.0.0.1", () => {
|
|
119
|
+
server.off("error", reject);
|
|
120
|
+
resolve();
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const TOKEN_TTL = "12h";
|
|
125
|
+
/** Renew two hours before the 12-hour TTL, leaving room for retries. */
|
|
126
|
+
const TOKEN_RENEW_AFTER_MS = 600 * 60 * 1e3;
|
|
127
|
+
const TOKEN_RENEW_CHECK_MS = 30 * 1e3;
|
|
128
|
+
const KEEPALIVE_RETRY_MS = 5 * 1e3;
|
|
129
|
+
/** The keepalive ends on its own after this, in case the process dies without cleaning up. */
|
|
130
|
+
const KEEPALIVE_MAX_SECONDS = 2160 * 60;
|
|
131
|
+
/**
|
|
132
|
+
* Serves `port` of a running sandbox on localhost without making it public,
|
|
133
|
+
* until {@link ForwardedPort.close}. The access token is renewed before it
|
|
134
|
+
* expires.
|
|
135
|
+
*/
|
|
136
|
+
async function forwardPort(sandbox, port, options = {}) {
|
|
137
|
+
const warn = options.onWarning ?? (() => {});
|
|
138
|
+
const open = options.openTunnel ?? openPortTunnel;
|
|
139
|
+
let access = await sandbox.createPortToken(port, { ttl: TOKEN_TTL });
|
|
140
|
+
const tunnelOptions = (localPort) => ({
|
|
141
|
+
hostname: access.hostname,
|
|
142
|
+
portToken: access.token,
|
|
143
|
+
localPort,
|
|
144
|
+
onActivity: options.onActivity
|
|
145
|
+
});
|
|
146
|
+
let tunnel;
|
|
147
|
+
try {
|
|
148
|
+
tunnel = await open(tunnelOptions(options.localPort ?? port)).catch((error) => {
|
|
149
|
+
if (options.localPort !== void 0 || error.code !== "EADDRINUSE" && error.code !== "EACCES") throw error;
|
|
150
|
+
return open(tunnelOptions(0));
|
|
151
|
+
});
|
|
152
|
+
} catch (error) {
|
|
153
|
+
await sandbox.deletePortToken(access.id).catch(() => {});
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
let closing = false;
|
|
157
|
+
let wakeSleeper;
|
|
158
|
+
const pause = (ms) => new Promise((resolve) => {
|
|
159
|
+
const timer = setTimeout(resolve, ms);
|
|
160
|
+
timer.unref?.();
|
|
161
|
+
wakeSleeper = () => {
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
resolve();
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
let keepalive;
|
|
167
|
+
const keepAwake = options.keepAwake === false ? void 0 : (async () => {
|
|
168
|
+
let failures = 0;
|
|
169
|
+
while (!closing) {
|
|
170
|
+
try {
|
|
171
|
+
const started = await sandbox.run("exec tail -f /dev/null", {
|
|
172
|
+
collectOutput: false,
|
|
173
|
+
timeoutSeconds: KEEPALIVE_MAX_SECONDS
|
|
174
|
+
});
|
|
175
|
+
if (closing) {
|
|
176
|
+
await started.kill().catch(() => {});
|
|
177
|
+
await started.disconnect().catch(() => {});
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
keepalive = started;
|
|
181
|
+
if (failures > 0) warn("The sandbox is being kept awake again.");
|
|
182
|
+
failures = 0;
|
|
183
|
+
await keepalive.wait();
|
|
184
|
+
} catch {}
|
|
185
|
+
if (closing) break;
|
|
186
|
+
if (failures++ === 0) warn("Lost the connection keeping the sandbox awake; retrying. It may pause after its idle timeout until then.");
|
|
187
|
+
await pause(Math.min(KEEPALIVE_RETRY_MS * failures, 6e4));
|
|
188
|
+
}
|
|
189
|
+
})();
|
|
190
|
+
let renewAt = Date.now() + TOKEN_RENEW_AFTER_MS;
|
|
191
|
+
let renewFailures = 0;
|
|
192
|
+
let renewing;
|
|
193
|
+
const renew = () => {
|
|
194
|
+
renewing = (async () => {
|
|
195
|
+
const next = await sandbox.createPortToken(port, { ttl: TOKEN_TTL });
|
|
196
|
+
if (closing) {
|
|
197
|
+
await sandbox.deletePortToken(next.id).catch(() => {});
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
tunnel.setPortToken(next.token);
|
|
201
|
+
const previous = access;
|
|
202
|
+
access = next;
|
|
203
|
+
renewAt = Date.now() + TOKEN_RENEW_AFTER_MS;
|
|
204
|
+
if (renewFailures > 0) warn("Renewed the tunnel's access token.");
|
|
205
|
+
renewFailures = 0;
|
|
206
|
+
await sandbox.deletePortToken(previous.id).catch(() => {});
|
|
207
|
+
})().catch(() => {
|
|
208
|
+
if (renewFailures++ === 0) warn("Couldn't renew the tunnel's access token; retrying. New connections fail if it expires first.");
|
|
209
|
+
renewAt = Date.now() + Math.min(6e4 * renewFailures, 10 * 6e4);
|
|
210
|
+
}).finally(() => {
|
|
211
|
+
renewing = void 0;
|
|
212
|
+
});
|
|
213
|
+
};
|
|
214
|
+
const renewal = setInterval(() => {
|
|
215
|
+
if (!renewing && !closing && Date.now() >= renewAt) renew();
|
|
216
|
+
}, TOKEN_RENEW_CHECK_MS);
|
|
217
|
+
renewal.unref?.();
|
|
218
|
+
let closed;
|
|
219
|
+
return {
|
|
220
|
+
localPort: tunnel.port,
|
|
221
|
+
url: `http://127.0.0.1:${tunnel.port}`,
|
|
222
|
+
close: () => closed ??= (async () => {
|
|
223
|
+
clearInterval(renewal);
|
|
224
|
+
closing = true;
|
|
225
|
+
wakeSleeper?.();
|
|
226
|
+
await renewing;
|
|
227
|
+
await tunnel.close();
|
|
228
|
+
await keepalive?.kill().catch(() => {});
|
|
229
|
+
await keepalive?.disconnect().catch(() => {});
|
|
230
|
+
await keepAwake;
|
|
231
|
+
await sandbox.deletePortToken(access.id).catch(() => {});
|
|
232
|
+
})()
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Starts a sandbox's desktop and serves it on 127.0.0.1 (port 6080 unless
|
|
237
|
+
* taken). Open `viewerUrl` in a browser on this machine.
|
|
238
|
+
*/
|
|
239
|
+
async function openDesktopTunnel(sandbox, options = {}) {
|
|
240
|
+
const { token } = await sandbox.desktop.start();
|
|
241
|
+
const forwarded = await forwardPort(sandbox, DESKTOP_PORT, options);
|
|
242
|
+
return {
|
|
243
|
+
...forwarded,
|
|
244
|
+
viewerUrl: `${forwarded.url}${desktopViewerPath(token)}`
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
//#endregion
|
|
248
|
+
export { addRequestHeader, forwardPort, isLocalHost, openDesktopTunnel, openPortTunnel };
|