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.
@@ -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,77 @@
1
+ import { Pt as Sandbox } from "./archil-DHPfg1b9.cjs";
2
+ import { Duplex } from "node:stream";
3
+
4
+ //#region src/tunnel.d.ts
5
+ interface PortTunnelActivity {
6
+ /** Local connections currently open. */
7
+ connections: number;
8
+ /** Of those, connections upgraded to WebSockets (a noVNC viewer holds one). */
9
+ websockets: number;
10
+ }
11
+ interface PortTunnel {
12
+ /** Local port the tunnel listens on. */
13
+ port: number;
14
+ /** Use `token` for connections opened from now on (existing ones stay authenticated). */
15
+ setPortToken(token: string): void;
16
+ close(): Promise<void>;
17
+ }
18
+ interface PortTunnelOptions {
19
+ /** `<port>-<route>.<zone>` hostname returned with the port token. */
20
+ hostname: string;
21
+ portToken: string;
22
+ /** Local port to listen on; 0 picks a free one. */
23
+ localPort: number;
24
+ onActivity?: (activity: PortTunnelActivity) => void;
25
+ /** Opens the upstream connection; tests replace the TLS dial. */
26
+ connectUpstream?: (hostname: string) => Duplex;
27
+ }
28
+ declare function openPortTunnel(options: PortTunnelOptions): Promise<PortTunnel>;
29
+ /** Whether `host` (a Host header) names this machine's loopback on `port`. */
30
+ declare function isLocalHost(host: string | undefined, port: number): boolean;
31
+ /** Inserts `header` after the request line of the buffered request head. */
32
+ declare function addRequestHeader(head: Buffer, header: string): Buffer;
33
+ interface ForwardPortOptions {
34
+ /** Local port. Defaults to the sandbox port, or any free port if that one is taken or privileged. */
35
+ localPort?: number;
36
+ /**
37
+ * Hold a process connection for the forward's lifetime so the sandbox
38
+ * doesn't idle-pause: its idle timer only runs while it has no process
39
+ * connections, and tunnel traffic isn't one. Defaults to true.
40
+ */
41
+ keepAwake?: boolean;
42
+ /** Called whenever local connections open or close. */
43
+ onActivity?: (activity: PortTunnelActivity) => void;
44
+ /** Called for problems that don't stop the forward (keepalive or token renewal failures). */
45
+ onWarning?: (message: string) => void;
46
+ /** @internal Replaces the local listener; for tests. */
47
+ openTunnel?: (options: PortTunnelOptions) => Promise<PortTunnel>;
48
+ }
49
+ interface ForwardedPort {
50
+ /** Port listening on 127.0.0.1. */
51
+ localPort: number;
52
+ /**
53
+ * `http://127.0.0.1:<localPort>`. Not `localhost`, which can resolve to ::1,
54
+ * where another local server may hold the same port.
55
+ */
56
+ url: string;
57
+ /**
58
+ * Stops listening, ends the keepalive, and revokes the access token. The
59
+ * sandbox's other process connections are left alone.
60
+ */
61
+ close(): Promise<void>;
62
+ }
63
+ /**
64
+ * Serves `port` of a running sandbox on localhost without making it public,
65
+ * until {@link ForwardedPort.close}. The access token is renewed before it
66
+ * expires.
67
+ */
68
+ declare function forwardPort(sandbox: Sandbox, port: number, options?: ForwardPortOptions): Promise<ForwardedPort>;
69
+ /**
70
+ * Starts a sandbox's desktop and serves it on 127.0.0.1 (port 6080 unless
71
+ * taken). Open `viewerUrl` in a browser on this machine.
72
+ */
73
+ declare function openDesktopTunnel(sandbox: Sandbox, options?: ForwardPortOptions): Promise<ForwardedPort & {
74
+ viewerUrl: string;
75
+ }>;
76
+ //#endregion
77
+ export { ForwardPortOptions, ForwardedPort, PortTunnel, PortTunnelActivity, PortTunnelOptions, addRequestHeader, forwardPort, isLocalHost, openDesktopTunnel, openPortTunnel };
@@ -0,0 +1,77 @@
1
+ import { Pt as Sandbox } from "./archil-CenIy1WD.mjs";
2
+ import { Duplex } from "node:stream";
3
+
4
+ //#region src/tunnel.d.ts
5
+ interface PortTunnelActivity {
6
+ /** Local connections currently open. */
7
+ connections: number;
8
+ /** Of those, connections upgraded to WebSockets (a noVNC viewer holds one). */
9
+ websockets: number;
10
+ }
11
+ interface PortTunnel {
12
+ /** Local port the tunnel listens on. */
13
+ port: number;
14
+ /** Use `token` for connections opened from now on (existing ones stay authenticated). */
15
+ setPortToken(token: string): void;
16
+ close(): Promise<void>;
17
+ }
18
+ interface PortTunnelOptions {
19
+ /** `<port>-<route>.<zone>` hostname returned with the port token. */
20
+ hostname: string;
21
+ portToken: string;
22
+ /** Local port to listen on; 0 picks a free one. */
23
+ localPort: number;
24
+ onActivity?: (activity: PortTunnelActivity) => void;
25
+ /** Opens the upstream connection; tests replace the TLS dial. */
26
+ connectUpstream?: (hostname: string) => Duplex;
27
+ }
28
+ declare function openPortTunnel(options: PortTunnelOptions): Promise<PortTunnel>;
29
+ /** Whether `host` (a Host header) names this machine's loopback on `port`. */
30
+ declare function isLocalHost(host: string | undefined, port: number): boolean;
31
+ /** Inserts `header` after the request line of the buffered request head. */
32
+ declare function addRequestHeader(head: Buffer, header: string): Buffer;
33
+ interface ForwardPortOptions {
34
+ /** Local port. Defaults to the sandbox port, or any free port if that one is taken or privileged. */
35
+ localPort?: number;
36
+ /**
37
+ * Hold a process connection for the forward's lifetime so the sandbox
38
+ * doesn't idle-pause: its idle timer only runs while it has no process
39
+ * connections, and tunnel traffic isn't one. Defaults to true.
40
+ */
41
+ keepAwake?: boolean;
42
+ /** Called whenever local connections open or close. */
43
+ onActivity?: (activity: PortTunnelActivity) => void;
44
+ /** Called for problems that don't stop the forward (keepalive or token renewal failures). */
45
+ onWarning?: (message: string) => void;
46
+ /** @internal Replaces the local listener; for tests. */
47
+ openTunnel?: (options: PortTunnelOptions) => Promise<PortTunnel>;
48
+ }
49
+ interface ForwardedPort {
50
+ /** Port listening on 127.0.0.1. */
51
+ localPort: number;
52
+ /**
53
+ * `http://127.0.0.1:<localPort>`. Not `localhost`, which can resolve to ::1,
54
+ * where another local server may hold the same port.
55
+ */
56
+ url: string;
57
+ /**
58
+ * Stops listening, ends the keepalive, and revokes the access token. The
59
+ * sandbox's other process connections are left alone.
60
+ */
61
+ close(): Promise<void>;
62
+ }
63
+ /**
64
+ * Serves `port` of a running sandbox on localhost without making it public,
65
+ * until {@link ForwardedPort.close}. The access token is renewed before it
66
+ * expires.
67
+ */
68
+ declare function forwardPort(sandbox: Sandbox, port: number, options?: ForwardPortOptions): Promise<ForwardedPort>;
69
+ /**
70
+ * Starts a sandbox's desktop and serves it on 127.0.0.1 (port 6080 unless
71
+ * taken). Open `viewerUrl` in a browser on this machine.
72
+ */
73
+ declare function openDesktopTunnel(sandbox: Sandbox, options?: ForwardPortOptions): Promise<ForwardedPort & {
74
+ viewerUrl: string;
75
+ }>;
76
+ //#endregion
77
+ export { ForwardPortOptions, ForwardedPort, PortTunnel, PortTunnelActivity, PortTunnelOptions, addRequestHeader, forwardPort, isLocalHost, openDesktopTunnel, 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "disk",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "description": "Pure-JS client and CLIs for Archil disks and sandboxes",
5
5
  "keywords": [
6
6
  "archil",
@@ -36,7 +36,17 @@
36
36
  },
37
37
  "import": "./dist/internal/tools.mjs",
38
38
  "require": "./dist/internal/tools.cjs"
39
- }
39
+ },
40
+ "./tunnel": {
41
+ "types": "./dist/tunnel.d.mts",
42
+ "node": {
43
+ "import": "./dist/node/tunnel.mjs",
44
+ "require": "./dist/node/tunnel.cjs"
45
+ },
46
+ "import": "./dist/tunnel.mjs",
47
+ "require": "./dist/tunnel.cjs"
48
+ },
49
+ "./archil-cli": "./dist/archil-cli.mjs"
40
50
  },
41
51
  "bin": {
42
52
  "disk": "./dist/cli.mjs",