disk 1.13.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.
@@ -0,0 +1,28 @@
1
+ //#region src/paths.ts
2
+ /**
3
+ * Normalize a filesystem path to its segments, resolving "." and ".." (so a
4
+ * path means the same as in a shell, and ".." can't escape above the root) and
5
+ * optionally stripping a shell-style mount prefix (e.g. "/mnt" or "/mnt/archil")
6
+ * so a path copied from a `run_bash` command resolves the same way.
7
+ *
8
+ * toSegments("/a/b/../c") -> ["a", "c"]
9
+ * toSegments("/mnt/x", "/mnt") -> ["x"]
10
+ * toSegments("/../../etc/x") -> ["etc", "x"]
11
+ */
12
+ function toSegments(path, containerRoot) {
13
+ let p = (path ?? "").trim();
14
+ if (containerRoot) {
15
+ const root = containerRoot.replace(/\/+$/, "");
16
+ if (p === root) p = "/";
17
+ else if (p.startsWith(root + "/")) p = p.slice(root.length);
18
+ }
19
+ const resolved = [];
20
+ for (const seg of p.split("/")) {
21
+ if (seg === "" || seg === ".") continue;
22
+ if (seg === "..") resolved.pop();
23
+ else resolved.push(seg);
24
+ }
25
+ return resolved;
26
+ }
27
+ //#endregion
28
+ export { toSegments as t };
@@ -0,0 +1,150 @@
1
+ //#region src/sandbox-desktop.ts
2
+ /**
3
+ * Sandbox desktops: a Linux desktop (Ubuntu, XFCE, Firefox) served over VNC
4
+ * through noVNC on {@link DESKTOP_PORT}, from the image at
5
+ * {@link DESKTOP_IMAGE} (github.com/archil-data/sandbox-desktop). Inside the
6
+ * sandbox, `desktopctl` runs the desktop as supervised services; the noVNC
7
+ * server only connects a viewer that presents the desktop's token.
8
+ *
9
+ * Everything here runs commands through the sandbox process API, so it works
10
+ * wherever the SDK does. To view a private desktop from Node, see
11
+ * `openDesktopTunnel` in `disk/tunnel`.
12
+ */
13
+ const DESKTOP_IMAGE = "ghcr.io/archil-data/sandbox-desktop:latest";
14
+ const DESKTOP_PORT = 6080;
15
+ /** A browser on the desktop is sluggish with less. */
16
+ const DESKTOP_VCPUS = 2;
17
+ const DESKTOP_MEMORY_MIB = 4096;
18
+ /**
19
+ * Session cap for desktops. Viewer traffic doesn't count as sandbox activity,
20
+ * so desktops run with idle expiry off and this cap instead.
21
+ */
22
+ const DESKTOP_MAX_TTL_SECONDS = 14400;
23
+ const COMMAND_NOT_FOUND = 127;
24
+ const DISPLAY = "DISPLAY=:1";
25
+ const KEYS = /^[A-Za-z0-9_+ ]+$/;
26
+ /** Path on the desktop's noVNC server that opens the viewer and connects with `token`. */
27
+ function desktopViewerPath(token) {
28
+ return `/vnc.html?${new URLSearchParams({
29
+ autoconnect: "1",
30
+ resize: "remote",
31
+ reconnect: "1",
32
+ path: `websockify?token=${token}`
33
+ })}`;
34
+ }
35
+ var DesktopNotInstalledError = class extends Error {
36
+ constructor(sandboxName) {
37
+ super(`Sandbox '${sandboxName}' doesn't have the Archil desktop installed; create it with desktop: true or from an image based on ${DESKTOP_IMAGE}`);
38
+ this.name = "DesktopNotInstalledError";
39
+ }
40
+ };
41
+ /** The desktop of one sandbox: `sandbox.desktop`. */
42
+ var SandboxDesktop = class {
43
+ sandbox;
44
+ /** @internal */
45
+ constructor(sandbox) {
46
+ this.sandbox = sandbox;
47
+ }
48
+ /**
49
+ * Starts the desktop if it isn't running (safe to call repeatedly) and
50
+ * returns the viewer token. Anyone holding the token can view and control
51
+ * the desktop through a link to its port.
52
+ */
53
+ async start() {
54
+ const { token } = JSON.parse(await this.run("desktopctl up"));
55
+ return { token };
56
+ }
57
+ /** The current viewer token. `rotate` replaces it first; a fork should rotate so it doesn't share its parent's. */
58
+ async token(options = {}) {
59
+ return (await this.run(options.rotate ? "desktopctl token --rotate" : "desktopctl token")).trim();
60
+ }
61
+ /**
62
+ * Publishes the desktop on a public HTTPS hostname and returns a viewer
63
+ * link. Anyone with the link can see and control the desktop until
64
+ * {@link unshare}.
65
+ */
66
+ async share() {
67
+ const { token } = await this.start();
68
+ return `https://${await this.sandbox.exposePort(DESKTOP_PORT)}${desktopViewerPath(token)}`;
69
+ }
70
+ /** Removes the public hostname, invalidates every existing link, and disconnects current viewers. */
71
+ async unshare() {
72
+ await this.sandbox.unexposePort(DESKTOP_PORT);
73
+ await this.run("desktopctl revoke");
74
+ }
75
+ /** A PNG of the whole screen. */
76
+ async screenshot() {
77
+ return decodeBase64((await this.run(`${DISPLAY} scrot -o /tmp/.archil-desktop-shot.png && base64 -w0 /tmp/.archil-desktop-shot.png`)).trim());
78
+ }
79
+ /** The screen size in pixels. */
80
+ async size() {
81
+ const [width, height] = (await this.run(`${DISPLAY} xdotool getdisplaygeometry`)).trim().split(/\s+/).map(Number);
82
+ return {
83
+ width,
84
+ height
85
+ };
86
+ }
87
+ async moveMouse(x, y) {
88
+ await this.run(`${DISPLAY} xdotool mousemove ${coordinate(x)} ${coordinate(y)}`);
89
+ }
90
+ async click(x, y, options = {}) {
91
+ const button = {
92
+ left: 1,
93
+ middle: 2,
94
+ right: 3
95
+ }[options.button ?? "left"];
96
+ const repeat = options.double ? " --repeat 2" : "";
97
+ await this.run(`${DISPLAY} xdotool mousemove ${coordinate(x)} ${coordinate(y)} click${repeat} ${button}`);
98
+ }
99
+ async scroll(direction, amount = 3) {
100
+ const button = {
101
+ up: 4,
102
+ down: 5,
103
+ left: 6,
104
+ right: 7
105
+ }[direction];
106
+ await this.run(`${DISPLAY} xdotool click --repeat ${count(amount)} ${button}`);
107
+ }
108
+ /** Types `text` into the focused window. */
109
+ async type(text) {
110
+ await this.run(`${DISPLAY} xdotool type --delay 12 -- "$ARCHIL_DESKTOP_TEXT"`, { ARCHIL_DESKTOP_TEXT: text });
111
+ }
112
+ /** Presses a key or chord in xdotool's syntax, e.g. "Return", "ctrl+l", "ctrl+shift+t". */
113
+ async key(keys) {
114
+ if (!KEYS.test(keys)) throw new Error(`Invalid key '${keys}'; use names like Return, ctrl+l, or alt+F4`);
115
+ await this.run(`${DISPLAY} xdotool key -- $ARCHIL_DESKTOP_KEYS`, { ARCHIL_DESKTOP_KEYS: keys });
116
+ }
117
+ /** Starts a program on the desktop as its user, e.g. `["firefox", "https://archil.com"]`. It keeps running after this returns. */
118
+ async launch(argv) {
119
+ if (argv.length === 0) throw new Error("launch needs a program to run");
120
+ await this.run(`desktopctl launch ${argv.map(shellQuote).join(" ")}`);
121
+ }
122
+ async run(command, env) {
123
+ const result = await this.sandbox.exec(command, env ? { env } : void 0);
124
+ if (result.exitCode === COMMAND_NOT_FOUND) throw new DesktopNotInstalledError(this.sandbox.name);
125
+ if (result.exitCode !== 0) {
126
+ const name = command.split(" ").find((word) => !word.includes("="));
127
+ throw new Error(`${name} failed in sandbox '${this.sandbox.name}': ${(result.stderr || result.stdout).trim()}`);
128
+ }
129
+ return result.stdout;
130
+ }
131
+ };
132
+ function coordinate(value) {
133
+ if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid screen coordinate ${value}`);
134
+ return Math.round(value);
135
+ }
136
+ function count(value) {
137
+ if (!Number.isInteger(value) || value < 1 || value > 100) throw new Error(`Scroll amount must be an integer from 1 to 100`);
138
+ return value;
139
+ }
140
+ function shellQuote(value) {
141
+ return `'${value.replaceAll("'", `'\\''`)}'`;
142
+ }
143
+ function decodeBase64(text) {
144
+ const binary = atob(text);
145
+ const bytes = new Uint8Array(binary.length);
146
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
147
+ return bytes;
148
+ }
149
+ //#endregion
150
+ export { DESKTOP_VCPUS as a, desktopViewerPath as c, DESKTOP_PORT as i, DESKTOP_MAX_TTL_SECONDS as n, DesktopNotInstalledError as o, DESKTOP_MEMORY_MIB as r, SandboxDesktop as s, DESKTOP_IMAGE as t };
@@ -0,0 +1,197 @@
1
+ //#region src/sandbox-desktop.ts
2
+ /**
3
+ * Sandbox desktops: a Linux desktop (Ubuntu, XFCE, Firefox) served over VNC
4
+ * through noVNC on {@link DESKTOP_PORT}, from the image at
5
+ * {@link DESKTOP_IMAGE} (github.com/archil-data/sandbox-desktop). Inside the
6
+ * sandbox, `desktopctl` runs the desktop as supervised services; the noVNC
7
+ * server only connects a viewer that presents the desktop's token.
8
+ *
9
+ * Everything here runs commands through the sandbox process API, so it works
10
+ * wherever the SDK does. To view a private desktop from Node, see
11
+ * `openDesktopTunnel` in `disk/tunnel`.
12
+ */
13
+ const DESKTOP_IMAGE = "ghcr.io/archil-data/sandbox-desktop:latest";
14
+ const DESKTOP_PORT = 6080;
15
+ /** A browser on the desktop is sluggish with less. */
16
+ const DESKTOP_VCPUS = 2;
17
+ const DESKTOP_MEMORY_MIB = 4096;
18
+ /**
19
+ * Session cap for desktops. Viewer traffic doesn't count as sandbox activity,
20
+ * so desktops run with idle expiry off and this cap instead.
21
+ */
22
+ const DESKTOP_MAX_TTL_SECONDS = 14400;
23
+ const COMMAND_NOT_FOUND = 127;
24
+ const DISPLAY = "DISPLAY=:1";
25
+ const KEYS = /^[A-Za-z0-9_+ ]+$/;
26
+ /** Path on the desktop's noVNC server that opens the viewer and connects with `token`. */
27
+ function desktopViewerPath(token) {
28
+ return `/vnc.html?${new URLSearchParams({
29
+ autoconnect: "1",
30
+ resize: "remote",
31
+ reconnect: "1",
32
+ path: `websockify?token=${token}`
33
+ })}`;
34
+ }
35
+ var DesktopNotInstalledError = class extends Error {
36
+ constructor(sandboxName) {
37
+ super(`Sandbox '${sandboxName}' doesn't have the Archil desktop installed; create it with desktop: true or from an image based on ${DESKTOP_IMAGE}`);
38
+ this.name = "DesktopNotInstalledError";
39
+ }
40
+ };
41
+ /** The desktop of one sandbox: `sandbox.desktop`. */
42
+ var SandboxDesktop = class {
43
+ sandbox;
44
+ /** @internal */
45
+ constructor(sandbox) {
46
+ this.sandbox = sandbox;
47
+ }
48
+ /**
49
+ * Starts the desktop if it isn't running (safe to call repeatedly) and
50
+ * returns the viewer token. Anyone holding the token can view and control
51
+ * the desktop through a link to its port.
52
+ */
53
+ async start() {
54
+ const { token } = JSON.parse(await this.run("desktopctl up"));
55
+ return { token };
56
+ }
57
+ /** The current viewer token. `rotate` replaces it first; a fork should rotate so it doesn't share its parent's. */
58
+ async token(options = {}) {
59
+ return (await this.run(options.rotate ? "desktopctl token --rotate" : "desktopctl token")).trim();
60
+ }
61
+ /**
62
+ * Publishes the desktop on a public HTTPS hostname and returns a viewer
63
+ * link. Anyone with the link can see and control the desktop until
64
+ * {@link unshare}.
65
+ */
66
+ async share() {
67
+ const { token } = await this.start();
68
+ return `https://${await this.sandbox.exposePort(DESKTOP_PORT)}${desktopViewerPath(token)}`;
69
+ }
70
+ /** Removes the public hostname, invalidates every existing link, and disconnects current viewers. */
71
+ async unshare() {
72
+ await this.sandbox.unexposePort(DESKTOP_PORT);
73
+ await this.run("desktopctl revoke");
74
+ }
75
+ /** A PNG of the whole screen. */
76
+ async screenshot() {
77
+ return decodeBase64((await this.run(`${DISPLAY} scrot -o /tmp/.archil-desktop-shot.png && base64 -w0 /tmp/.archil-desktop-shot.png`)).trim());
78
+ }
79
+ /** The screen size in pixels. */
80
+ async size() {
81
+ const [width, height] = (await this.run(`${DISPLAY} xdotool getdisplaygeometry`)).trim().split(/\s+/).map(Number);
82
+ return {
83
+ width,
84
+ height
85
+ };
86
+ }
87
+ async moveMouse(x, y) {
88
+ await this.run(`${DISPLAY} xdotool mousemove ${coordinate(x)} ${coordinate(y)}`);
89
+ }
90
+ async click(x, y, options = {}) {
91
+ const button = {
92
+ left: 1,
93
+ middle: 2,
94
+ right: 3
95
+ }[options.button ?? "left"];
96
+ const repeat = options.double ? " --repeat 2" : "";
97
+ await this.run(`${DISPLAY} xdotool mousemove ${coordinate(x)} ${coordinate(y)} click${repeat} ${button}`);
98
+ }
99
+ async scroll(direction, amount = 3) {
100
+ const button = {
101
+ up: 4,
102
+ down: 5,
103
+ left: 6,
104
+ right: 7
105
+ }[direction];
106
+ await this.run(`${DISPLAY} xdotool click --repeat ${count(amount)} ${button}`);
107
+ }
108
+ /** Types `text` into the focused window. */
109
+ async type(text) {
110
+ await this.run(`${DISPLAY} xdotool type --delay 12 -- "$ARCHIL_DESKTOP_TEXT"`, { ARCHIL_DESKTOP_TEXT: text });
111
+ }
112
+ /** Presses a key or chord in xdotool's syntax, e.g. "Return", "ctrl+l", "ctrl+shift+t". */
113
+ async key(keys) {
114
+ if (!KEYS.test(keys)) throw new Error(`Invalid key '${keys}'; use names like Return, ctrl+l, or alt+F4`);
115
+ await this.run(`${DISPLAY} xdotool key -- $ARCHIL_DESKTOP_KEYS`, { ARCHIL_DESKTOP_KEYS: keys });
116
+ }
117
+ /** Starts a program on the desktop as its user, e.g. `["firefox", "https://archil.com"]`. It keeps running after this returns. */
118
+ async launch(argv) {
119
+ if (argv.length === 0) throw new Error("launch needs a program to run");
120
+ await this.run(`desktopctl launch ${argv.map(shellQuote).join(" ")}`);
121
+ }
122
+ async run(command, env) {
123
+ const result = await this.sandbox.exec(command, env ? { env } : void 0);
124
+ if (result.exitCode === COMMAND_NOT_FOUND) throw new DesktopNotInstalledError(this.sandbox.name);
125
+ if (result.exitCode !== 0) {
126
+ const name = command.split(" ").find((word) => !word.includes("="));
127
+ throw new Error(`${name} failed in sandbox '${this.sandbox.name}': ${(result.stderr || result.stdout).trim()}`);
128
+ }
129
+ return result.stdout;
130
+ }
131
+ };
132
+ function coordinate(value) {
133
+ if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid screen coordinate ${value}`);
134
+ return Math.round(value);
135
+ }
136
+ function count(value) {
137
+ if (!Number.isInteger(value) || value < 1 || value > 100) throw new Error(`Scroll amount must be an integer from 1 to 100`);
138
+ return value;
139
+ }
140
+ function shellQuote(value) {
141
+ return `'${value.replaceAll("'", `'\\''`)}'`;
142
+ }
143
+ function decodeBase64(text) {
144
+ const binary = atob(text);
145
+ const bytes = new Uint8Array(binary.length);
146
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
147
+ return bytes;
148
+ }
149
+ //#endregion
150
+ Object.defineProperty(exports, "DESKTOP_IMAGE", {
151
+ enumerable: true,
152
+ get: function() {
153
+ return DESKTOP_IMAGE;
154
+ }
155
+ });
156
+ Object.defineProperty(exports, "DESKTOP_MAX_TTL_SECONDS", {
157
+ enumerable: true,
158
+ get: function() {
159
+ return DESKTOP_MAX_TTL_SECONDS;
160
+ }
161
+ });
162
+ Object.defineProperty(exports, "DESKTOP_MEMORY_MIB", {
163
+ enumerable: true,
164
+ get: function() {
165
+ return DESKTOP_MEMORY_MIB;
166
+ }
167
+ });
168
+ Object.defineProperty(exports, "DESKTOP_PORT", {
169
+ enumerable: true,
170
+ get: function() {
171
+ return DESKTOP_PORT;
172
+ }
173
+ });
174
+ Object.defineProperty(exports, "DESKTOP_VCPUS", {
175
+ enumerable: true,
176
+ get: function() {
177
+ return DESKTOP_VCPUS;
178
+ }
179
+ });
180
+ Object.defineProperty(exports, "DesktopNotInstalledError", {
181
+ enumerable: true,
182
+ get: function() {
183
+ return DesktopNotInstalledError;
184
+ }
185
+ });
186
+ Object.defineProperty(exports, "SandboxDesktop", {
187
+ enumerable: true,
188
+ get: function() {
189
+ return SandboxDesktop;
190
+ }
191
+ });
192
+ Object.defineProperty(exports, "desktopViewerPath", {
193
+ enumerable: true,
194
+ get: function() {
195
+ return desktopViewerPath;
196
+ }
197
+ });
@@ -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;