@fungi.computer/computer 0.16.2 → 0.16.3

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/Dockerfile CHANGED
@@ -38,7 +38,8 @@ FROM node:24.20.0-trixie-slim@sha256:a747ad80c8a161b650d79a6da9c422005b91148b18b
38
38
 
39
39
  RUN apt-get update \
40
40
  && apt-get install -y --no-install-recommends \
41
- fuse3 libfuse2t64 ca-certificates curl git procps tini \
41
+ fuse3 libfuse2t64 ca-certificates curl git procps tini openssh-server \
42
+ && rm -f /etc/ssh/ssh_host_* \
42
43
  && rm -rf /var/lib/apt/lists/*
43
44
 
44
45
  RUN npm install --global --no-fund --no-audit pnpm@11.24.0 \
@@ -59,12 +60,15 @@ COPY dist/apply-patch/LICENSE.codex /opt/fungi/fungi-apply-patch.LICENSE
59
60
  COPY --from=terminal /opt/fungi/node_modules /opt/fungi/node_modules
60
61
  COPY container/runtime-privileges.mjs /opt/fungi/
61
62
  COPY --from=terminal /opt/fungi/runtime-privileges.node /opt/fungi/
62
- COPY container/package.json container/computer-init.mjs container/computer-start.sh container/resource-bounds.mjs container/terminal-server.mjs container/terminal-runtime.mjs container/terminal-protocol.mjs /opt/fungi/
63
+ COPY container/package.json container/computer-init.mjs container/computer-start.sh container/resource-bounds.mjs container/terminal-server.mjs container/terminal-runtime.mjs container/terminal-protocol.mjs container/sshd_config /opt/fungi/
63
64
  COPY container/terminal-assets/bashrc container/terminal-assets/git-prompt.sh container/terminal-assets/global-tools.sh /opt/fungi/terminal-assets/
64
65
  RUN chmod -R a+rX /opt/fungi \
65
66
  && printf '\n. /opt/fungi/terminal-assets/bashrc\n' >> /etc/bash.bashrc \
66
67
  && printf '. /opt/fungi/terminal-assets/global-tools.sh\n. /opt/fungi/terminal-assets/bashrc\n' > /etc/profile.d/fungi-terminal.sh
67
68
 
69
+ # openssh-server is installed only for `sshd -i`, which terminal-server.mjs runs
70
+ # as the runtime user for one admitted connection. No sshd service starts, and no
71
+ # host key ships in the image: vmd supplies each VM's key at boot.
68
72
  # No customer process can invoke a setuid/setgid helper, including fusermount.
69
73
  # FUSE is mounted while init is root, before either runtime listener opens.
70
74
  RUN find / -xdev -perm /6000 -exec chmod a-s {} +
package/README.md CHANGED
@@ -273,6 +273,7 @@ were saved in a hosted Computer. Do not copy its temporary output into source.
273
273
  checks native workspace operations and reconstruction.
274
274
  [Process proof](test/process-proof.mjs) checks retained process identity against
275
275
  the real container. [Terminal proof](test/terminal-container-proof.mjs),
276
+ [SSH proof](test/ssh-container-proof.mjs) (the guest `sshd -i` behind `/ssh`),
276
277
  [resource proof](test/container-resource-proof.mjs) and
277
278
  [backend tests](test/computer-backends.test.mjs) cover their separate
278
279
  boundaries. The declared nightly egress proof is separate from the ordinary
@@ -21,6 +21,19 @@ mkdir -p /workspace
21
21
  chown "$uid:$uid" /workspace
22
22
  ulimit -Su "$pids_max"
23
23
  ulimit -Hu "$pids_max"
24
+ # vmd's guest config carries this VM's SSH host key, user CA and principals. The
25
+ # unprivileged `sshd -i` reads them from files only the runtime user can read; a
26
+ # Computer without them has no SSH, and terminal-server refuses /ssh.
27
+ ssh_source=/run/fungi-vm/ssh
28
+ ssh_directory=/run/fungi-ssh
29
+ rm -rf "$ssh_directory"
30
+ if [[ -d "$ssh_source" ]]; then
31
+ install -d -m 0700 -o "$uid" -g "$uid" "$ssh_directory"
32
+ for name in host_ed25519 user_ca.pub principals; do
33
+ [[ -f "$ssh_source/$name" ]] || continue
34
+ install -m 0600 -o "$uid" -g "$uid" "$ssh_source/$name" "$ssh_directory/$name"
35
+ done
36
+ fi
24
37
  export HOME=/workspace
25
38
  # The image's npm and pnpm prefixes are root-owned. Global installs go into
26
39
  # user-owned folders in the persistent home; npm and pnpm create them on first
@@ -0,0 +1,38 @@
1
+ # The Computer's guest sshd, run only as `sshd -i` by terminal-server.mjs for one
2
+ # Hub-admitted WebSocket at a time, as the unprivileged runtime user. It has no
3
+ # listening socket. A user is admitted only by an OpenSSH certificate signed by
4
+ # the host's CA whose principal is this VM's id; there are no other credentials.
5
+ # vmd writes the files below into the guest at boot; computer-start.sh copies
6
+ # them to files the runtime user owns.
7
+ HostKey /run/fungi-ssh/host_ed25519
8
+ TrustedUserCAKeys /run/fungi-ssh/user_ca.pub
9
+ AuthorizedPrincipalsFile /run/fungi-ssh/principals
10
+
11
+ # Authentication
12
+ AuthorizedKeysFile none
13
+ AuthenticationMethods publickey
14
+ PubkeyAuthentication yes
15
+ PasswordAuthentication no
16
+ KbdInteractiveAuthentication no
17
+ PermitEmptyPasswords no
18
+ PermitRootLogin no
19
+ UsePAM no
20
+ StrictModes yes
21
+ AllowUsers fungi
22
+
23
+ # Forwarding: listeners stay on the guest's own loopback
24
+ GatewayPorts no
25
+ AllowAgentForwarding no
26
+ AllowStreamLocalForwarding no
27
+ PermitTunnel no
28
+ X11Forwarding no
29
+
30
+ # Nothing the user or the client can set changes the login
31
+ PermitUserRC no
32
+ PermitUserEnvironment no
33
+ PrintMotd no
34
+ PidFile none
35
+ LogLevel VERBOSE
36
+
37
+ # scp and sftp clients use the SFTP protocol
38
+ Subsystem sftp internal-sftp
@@ -4,15 +4,21 @@
4
4
  // `{"type":"resize","cols":N,"rows":N}` resizes, and the server sends
5
5
  // `{"type":"ready","information":{...}}` with display facts,
6
6
  // `{"type":"exit","code":N}` and `{"type":"error"}`.
7
+ //
8
+ // `/ssh` is a second door on the same port: each WebSocket carries one raw SSH
9
+ // stream (binary frames only) to a fixed `sshd -i`, run as this process's
10
+ // unprivileged user. It listens on nothing and counts as a session.
11
+ import { spawn } from "node:child_process";
7
12
  import { Buffer } from "node:buffer";
8
- import { existsSync } from "node:fs";
13
+ import console from "node:console";
14
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
9
15
  import { createServer } from "node:http";
10
16
  import process from "node:process";
11
- import { clearInterval, setInterval } from "node:timers";
17
+ import { clearInterval, setInterval, setTimeout } from "node:timers";
12
18
  import { URL } from "node:url";
13
19
  import pty from "node-pty";
14
20
  import manifest from "./package.json" with { type: "json" };
15
- import { WebSocketServer } from "ws";
21
+ import { createWebSocketStream, WebSocketServer } from "ws";
16
22
  import {
17
23
  boundedInteger,
18
24
  parseResize,
@@ -21,12 +27,88 @@ import {
21
27
  } from "./terminal-protocol.mjs";
22
28
 
23
29
  const terminalShell = "/bin/bash";
30
+ /** The guest's `sshd -i`, with fixed argv; nothing a client sends reaches it. */
31
+ const sshd = "/usr/sbin/sshd";
32
+ const sshdArguments = ["-i", "-e", "-f", "/opt/fungi/sshd_config"];
33
+ /** What vmd supplies at boot (computer-start.sh); without them there is no SSH. */
34
+ const sshFiles = [
35
+ "/run/fungi-ssh/host_ed25519",
36
+ "/run/fungi-ssh/user_ca.pub",
37
+ "/run/fungi-ssh/principals",
38
+ ];
39
+ /** How long a hung-up SSH session's processes get after SIGTERM before SIGKILL. */
40
+ const sshKillGraceMs = 2_000;
24
41
  const maximumSessions = 16;
25
42
  const detachedLifetimeMs = 30 * 60 * 1_000;
26
43
  /** A client that cannot drain this much output reconnects and replays. */
27
44
  const maximumBufferedBytes = 4 * 1_024 * 1_024;
28
45
  const sessionPattern = /^[A-Za-z0-9._:-]{1,160}$/;
29
46
 
47
+ /**
48
+ * Every process below `root`, from /proc. sshd puts a session's command in a
49
+ * session of its own and ignores SIGTERM when it has no PTY, so neither the
50
+ * process group nor sshd's death reaches it: the tree is read while sshd lives.
51
+ */
52
+ function descendants(root) {
53
+ const children = new Map();
54
+ for (const name of readdirSync("/proc")) {
55
+ if (!/^[0-9]+$/u.test(name)) continue;
56
+ let stat;
57
+ try {
58
+ stat = readFileSync(`/proc/${name}/stat`, "utf8");
59
+ } catch (cause) {
60
+ // The process exited while the table was read.
61
+ if (cause.code === "ENOENT" || cause.code === "ESRCH") continue;
62
+ throw cause;
63
+ }
64
+ // "pid (comm) state ppid ...": comm may hold spaces and parentheses.
65
+ const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
66
+ const siblings = children.get(parent) ?? [];
67
+ siblings.push(Number(name));
68
+ children.set(parent, siblings);
69
+ }
70
+ const found = [];
71
+ const pending = [root];
72
+ while (pending.length > 0) {
73
+ for (const child of children.get(pending.pop()) ?? []) {
74
+ found.push(child);
75
+ pending.push(child);
76
+ }
77
+ }
78
+ return found;
79
+ }
80
+
81
+ function signal(pid, name) {
82
+ try {
83
+ process.kill(pid, name);
84
+ } catch (cause) {
85
+ // A process that is already gone is what cleanup wants.
86
+ if (cause.code !== "ESRCH")
87
+ console.error(`ssh cleanup could not signal ${String(pid)}`, cause);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * End an sshd and all it started: SIGTERM, then SIGKILL after a short grace.
93
+ * When sshd itself has already exited its children cannot be found, so the
94
+ * tree walk is skipped; after the grace sshd's own pid and group are left
95
+ * alone once it is gone (the number may be reused), while a descendant that
96
+ * was alive when the walk ran is still killed.
97
+ */
98
+ function killSshd(child) {
99
+ const pid = child.pid;
100
+ if (pid === undefined) return;
101
+ const exited = () => child.exitCode !== null || child.signalCode !== null;
102
+ const doomed = exited() ? [] : [pid, ...descendants(pid)];
103
+ signal(-pid, "SIGTERM");
104
+ for (const target of doomed) signal(target, "SIGTERM");
105
+ setTimeout(() => {
106
+ if (!exited()) signal(-pid, "SIGKILL");
107
+ for (const target of doomed)
108
+ if (target !== pid || !exited()) signal(target, "SIGKILL");
109
+ }, sshKillGraceMs).unref();
110
+ }
111
+
30
112
  function send(socket, frame) {
31
113
  if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(frame));
32
114
  }
@@ -41,24 +123,30 @@ function shellEnvironment(labels) {
41
123
  return environment;
42
124
  }
43
125
 
44
- /** Owns every PTY session in this container; nothing else spawns shells. */
126
+ /**
127
+ * Owns every PTY session in this container, and every `sshd -i` that serves an
128
+ * attached SSH socket. Nothing else spawns shells or login daemons.
129
+ */
45
130
  class TerminalSessions {
46
131
  #sessions = new Map();
132
+ #ssh = new Set();
133
+ #spawnSshd;
47
134
  #spawn;
48
135
  #now;
49
136
 
50
- constructor(spawn, now) {
137
+ constructor(spawn, now, spawnSshd = spawnFixedSshd) {
51
138
  this.#spawn = spawn;
52
139
  this.#now = now;
140
+ this.#spawnSshd = spawnSshd;
53
141
  }
54
142
 
55
143
  get size() {
56
- return this.#sessions.size;
144
+ return this.#sessions.size + this.#ssh.size;
57
145
  }
58
146
 
59
147
  /** Sessions with a socket attached now; detached shells do not count. */
60
148
  get attached() {
61
- let attached = 0;
149
+ let attached = this.#ssh.size;
62
150
  for (const session of this.#sessions.values())
63
151
  if (session.socket !== null) attached += 1;
64
152
  return attached;
@@ -112,6 +200,39 @@ class TerminalSessions {
112
200
  });
113
201
  }
114
202
 
203
+ /**
204
+ * Serve one SSH stream: a fresh `sshd -i` whose stdin and stdout are this
205
+ * socket's binary frames. It ends with either side, and never outlives it.
206
+ */
207
+ attachSsh(socket) {
208
+ if (!this.#makeRoom()) {
209
+ send(socket, { type: "error", message: "terminal session limit" });
210
+ socket.close(1013, "terminal session limit");
211
+ return;
212
+ }
213
+ const child = this.#spawnSshd();
214
+ const session = { socket, child };
215
+ this.#ssh.add(session);
216
+ const stream = createWebSocketStream(socket);
217
+ const finish = () => {
218
+ if (!this.#ssh.delete(session)) return;
219
+ stream.destroy();
220
+ killSshd(child);
221
+ if (socket.readyState === socket.OPEN) socket.close(1000, "sshd exited");
222
+ };
223
+ child.once("exit", finish);
224
+ child.once("error", finish);
225
+ socket.once("close", finish);
226
+ stream.on("error", finish);
227
+ child.stdin.on("error", finish);
228
+ child.stdout.on("error", finish);
229
+ stream.pipe(child.stdin);
230
+ child.stdout.pipe(stream);
231
+ socket.on("error", () => {
232
+ socket.terminate();
233
+ });
234
+ }
235
+
115
236
  /** Hang up sessions nobody has attached to for the detached lifetime. */
116
237
  reap() {
117
238
  const now = this.#now();
@@ -125,6 +246,10 @@ class TerminalSessions {
125
246
  }
126
247
 
127
248
  closeAll() {
249
+ for (const session of this.#ssh) {
250
+ session.socket.close(1001, "Computer stopping");
251
+ killSshd(session.child);
252
+ }
128
253
  for (const session of this.#sessions.values()) {
129
254
  session.socket?.close(1001, "Computer stopping");
130
255
  session.pty.kill("SIGHUP");
@@ -132,7 +257,7 @@ class TerminalSessions {
132
257
  }
133
258
 
134
259
  #makeRoom() {
135
- if (this.#sessions.size < maximumSessions) return true;
260
+ if (this.size < maximumSessions) return true;
136
261
  let oldest = null;
137
262
  for (const session of this.#sessions.values()) {
138
263
  if (session.detachedAt === null) continue;
@@ -186,7 +311,19 @@ class TerminalSessions {
186
311
  }
187
312
  }
188
313
 
189
- /** Serve `/health` and the `/pty` upgrade on one private container port. */
314
+ function spawnFixedSshd() {
315
+ return spawn(sshd, sshdArguments, {
316
+ cwd: "/",
317
+ // Its own process group, so one signal reaches sshd and its helpers.
318
+ detached: true,
319
+ // sshd's own log (VERBOSE, with each certificate's key id) goes to this
320
+ // process's stderr, which the container runtime collects.
321
+ stdio: ["pipe", "pipe", "inherit"],
322
+ env: { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin" },
323
+ });
324
+ }
325
+
326
+ /** Serve `/health` and the `/pty` and `/ssh` upgrades on one private container port. */
190
327
  export function startTerminalServer(port) {
191
328
  const sessions = new TerminalSessions(pty.spawn, () => Date.now());
192
329
  const sockets = new WebSocketServer({
@@ -209,6 +346,17 @@ export function startTerminalServer(port) {
209
346
  });
210
347
  server.on("upgrade", (request, socket, head) => {
211
348
  const url = new URL(request.url ?? "/", "http://localhost");
349
+ if (url.pathname === "/ssh") {
350
+ // A Computer whose boot supplied no SSH files has no SSH to offer.
351
+ if (!sshFiles.every((file) => existsSync(file))) {
352
+ socket.end("HTTP/1.1 503 Service Unavailable\r\n\r\n");
353
+ return;
354
+ }
355
+ sockets.handleUpgrade(request, socket, head, (client) => {
356
+ sessions.attachSsh(client);
357
+ });
358
+ return;
359
+ }
212
360
  const id = url.searchParams.get("session");
213
361
  if (url.pathname !== "/pty" || id === null || !sessionPattern.test(id)) {
214
362
  socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ import type { FilesPort } from "@fungi.computer/knapsack";
9
9
  import { z } from "zod";
10
10
  import { type ComputerExecutionBudget, type ComputerExecutionHostHooks, type ComputerExecRequest, type ComputerOperationResult, type ComputerFileReadInput, type ComputerFileByteReadInput, type ComputerFileReplacement, type ComputerFileReplacementResult, type ComputerValue, writeInputSchema, writeOutputSchema, processLogsOutputSchema, processWaitOutputSchema, type ComputerProcess } from "@fungi.computer/computer-contract";
11
11
  import { createWorkspaceFilesPort } from "./files.js";
12
- import { OnBoxVmContainerHost, type OnBoxVmEnv, type OnBoxVmPlacement } from "./on-box-vm.js";
12
+ import { OnBoxVmContainerHost, type OnBoxVmEnv, type OnBoxVmPlacement, type OnBoxVmSshCertificate } from "./on-box-vm.js";
13
13
  import { type AttachedBackend, type AttachedBackendView, type BackendNeed, type BackendRoute, type ComputerSize, type ContainerRuntimeStart, type HostedBacking } from "./computer-backends.js";
14
14
  import { LocalBackendConnections } from "./local-backend.js";
15
15
  /** Files needs only the native Workspace lease and its atomic replacement door. */
@@ -64,6 +64,10 @@ export declare class ComputerBackendUnavailableError extends Error {
64
64
  readonly code: "no_backend" | "backend_unavailable";
65
65
  constructor(code: "no_backend" | "backend_unavailable");
66
66
  }
67
+ /** SSH needs a guest sshd behind a host signer, which only an on-box VM has. */
68
+ export declare class ComputerSshUnavailableError extends Error {
69
+ constructor();
70
+ }
67
71
  declare class ComputerDurableObject extends DurableObject<ComputerEnv> {
68
72
  get bindings(): ComputerEnv;
69
73
  get state(): DurableObjectState;
@@ -347,6 +351,22 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
347
351
  * server, which keeps the PTY for `session` across socket reconnects.
348
352
  */
349
353
  protected terminalAfterAcceptance(request: Request, principalKey: string, accept: () => void): Promise<Response>;
354
+ /**
355
+ * Relay one authorized SSH transport to the guest terminal server's `/ssh`
356
+ * upgrade, which runs one `sshd -i` per connection as the runtime user. The
357
+ * SSH stream rides the WebSocket's binary frames; sshd authenticates it.
358
+ */
359
+ protected sshAfterAcceptance(request: Request, accept: () => void): Promise<Response>;
360
+ /**
361
+ * Ask this Computer's VM host to sign `publicKey` for its guest sshd. The
362
+ * caller decided who may; the host names this VM as the only principal.
363
+ */
364
+ protected sshCertificateAfterAcceptance(input: Readonly<{
365
+ publicKey: string;
366
+ keyId: string;
367
+ }>, accept: () => void): Promise<OnBoxVmSshCertificate & {
368
+ principal: string;
369
+ }>;
350
370
  protected withHostedResponse(_backing: HostedBacking, run: () => Promise<Response>): Promise<Response>;
351
371
  /** Host-owned display labels only; never credentials or provider URLs. */
352
372
  protected terminalDisplayEnvironment(): Promise<Record<string, string>>;
@@ -357,7 +377,7 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
357
377
  }
358
378
  export { WorkspaceProxy, WorkspaceServiceProxy };
359
379
  export { computerName, learnComputerName } from "./computer-name.js";
360
- export { OnBoxVmContainerHost, OnBoxVmTimeoutError, OnBoxVmUnavailableError, onBoxVmPlacement, onBoxVmIngress, type OnBoxVmEnv, type OnBoxVmOperation, type OnBoxVmState, } from "./on-box-vm.js";
380
+ export { OnBoxVmContainerHost, OnBoxVmTimeoutError, OnBoxVmUnavailableError, onBoxVmPlacement, onBoxVmIngress, type OnBoxVmEnv, type OnBoxVmOperation, type OnBoxVmSshCertificate, type OnBoxVmState, } from "./on-box-vm.js";
361
381
  export { computerContainerSleepAfterMs } from "./container-policy.js";
362
382
  export { isVaultExecutionContext, vaultExecutionContext, withVaultExecution, type VaultGrantPort, type VaultHolder, type VaultReferenceAdmission, type VaultSecretGrant, type VaultSubject, } from "./vault-references.js";
363
383
  export * from "./computer-backends.js";
package/dist/index.js CHANGED
@@ -262,6 +262,13 @@ export class ComputerBackendUnavailableError extends Error {
262
262
  this.name = "ComputerBackendUnavailableError";
263
263
  }
264
264
  }
265
+ /** SSH needs a guest sshd behind a host signer, which only an on-box VM has. */
266
+ export class ComputerSshUnavailableError extends Error {
267
+ constructor() {
268
+ super("SSH needs a hosted Computer");
269
+ this.name = "ComputerSshUnavailableError";
270
+ }
271
+ }
265
272
  class ComputerDurableObject extends DurableObject {
266
273
  get bindings() {
267
274
  return this.env;
@@ -1709,6 +1716,41 @@ export class ComputerDO extends ContainerComputer {
1709
1716
  if (!query.success) {
1710
1717
  return Response.json({ error: "invalid terminal options" }, { status: 400 });
1711
1718
  }
1719
+ return await this.#terminalServerUpgrade(request, accept, async () => {
1720
+ const target = new URL("http://localhost/pty");
1721
+ target.search = new URLSearchParams({
1722
+ ...(await this.terminalDisplayEnvironment()),
1723
+ session: await sha256(JSON.stringify([principalKey, query.data.session])),
1724
+ cols: String(query.data.cols),
1725
+ rows: String(query.data.rows),
1726
+ }).toString();
1727
+ return target;
1728
+ });
1729
+ }
1730
+ /**
1731
+ * Relay one authorized SSH transport to the guest terminal server's `/ssh`
1732
+ * upgrade, which runs one `sshd -i` per connection as the runtime user. The
1733
+ * SSH stream rides the WebSocket's binary frames; sshd authenticates it.
1734
+ */
1735
+ async sshAfterAcceptance(request, accept) {
1736
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket")
1737
+ return new Response("Expected WebSocket upgrade", { status: 426 });
1738
+ return await this.#terminalServerUpgrade(request, accept, () => Promise.resolve(new URL("http://localhost/ssh")));
1739
+ }
1740
+ /**
1741
+ * Ask this Computer's VM host to sign `publicKey` for its guest sshd. The
1742
+ * caller decided who may; the host names this VM as the only principal.
1743
+ */
1744
+ async sshCertificateAfterAcceptance(input, accept) {
1745
+ const hosted = this.hostedRoute();
1746
+ if (hosted?.backing.kind !== "on-box-vm")
1747
+ throw new ComputerSshUnavailableError();
1748
+ accept();
1749
+ const signed = await this.onBoxVmHost(hosted.backing.hostId).sshCertificate(input);
1750
+ return { ...signed, principal: this.state.id.toString() };
1751
+ }
1752
+ /** The hosted terminal server's upgrade, once the runtime answers a probe. */
1753
+ async #terminalServerUpgrade(request, accept, target) {
1712
1754
  const hosted = this.hostedRoute();
1713
1755
  if (hosted === undefined)
1714
1756
  return Response.json({ error: "Computer container is unavailable" }, { status: 502 });
@@ -1741,16 +1783,10 @@ export class ComputerDO extends ContainerComputer {
1741
1783
  // Hub rechecks current Computer/operation authority at the dispatch seam.
1742
1784
  accept();
1743
1785
  try {
1744
- const target = new URL("http://localhost/pty");
1745
- target.search = new URLSearchParams({
1746
- ...(await this.terminalDisplayEnvironment()),
1747
- session: await sha256(JSON.stringify([principalKey, query.data.session])),
1748
- cols: String(query.data.cols),
1749
- rows: String(query.data.rows),
1750
- }).toString();
1786
+ const url = await target();
1751
1787
  const response = await this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
1752
1788
  .port(computerTerminalPort)
1753
- .fetch(new Request(target, request)));
1789
+ .fetch(new Request(url, request)));
1754
1790
  if (response.status === 101)
1755
1791
  this.#startTerminalSync(hosted.backing);
1756
1792
  return response;
@@ -44,7 +44,13 @@ export declare function onBoxVmPlacement(env: OnBoxVmEnv, hostId: string | undef
44
44
  export declare class OnBoxVmUnavailableError extends Error {
45
45
  readonly operation: string;
46
46
  readonly status: number;
47
- constructor(operation: string, status: number, detail?: string);
47
+ /** The host's own words, up to 200 characters. */
48
+ readonly detail: string;
49
+ /** The host's typed refusal, such as `scratch_capacity`; null when it names none. */
50
+ readonly hostCode: string | null;
51
+ constructor(operation: string, status: number,
52
+ /** The host's own words, up to 200 characters. */
53
+ detail?: string);
48
54
  }
49
55
  declare const vmStateSchema: z.ZodObject<{
50
56
  running: z.ZodBoolean;
@@ -72,7 +78,14 @@ declare const vmInventorySchema: z.ZodArray<z.ZodObject<{
72
78
  }>;
73
79
  }, z.core.$strict>>;
74
80
  export type OnBoxVmInventory = z.infer<typeof vmInventorySchema>;
75
- export type OnBoxVmOperation = "status" | "start" | "restart" | "destroy" | "intercept" | "inventory";
81
+ export type OnBoxVmOperation = "status" | "start" | "restart" | "destroy" | "intercept" | "inventory" | "ssh-certificate";
82
+ /** vmd's signed answer: a user certificate for this VM and its per-boot host key. */
83
+ declare const vmSshCertificateSchema: z.ZodObject<{
84
+ certificate: z.ZodString;
85
+ serial: z.ZodString;
86
+ hostKey: z.ZodString;
87
+ }, z.core.$strict>;
88
+ export type OnBoxVmSshCertificate = z.infer<typeof vmSshCertificateSchema>;
76
89
  declare const OnBoxVmTimeoutError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
77
90
  readonly _tag: "OnBoxVmTimeoutError";
78
91
  } & Readonly<A>;
@@ -120,6 +133,15 @@ export declare class OnBoxVmContainerHost implements IWorkspaceContainerAPI {
120
133
  running(): Promise<boolean>;
121
134
  interceptOutboundHttp(host: string, workspace: WorkspaceRef): Promise<void>;
122
135
  interceptAllOutboundHttp(workspace: WorkspaceRef, token: string): Promise<void>;
136
+ /**
137
+ * Ask the host to sign `publicKey` for this VM's guest sshd. The host signs
138
+ * only this signed control request, names this VM as the one principal and
139
+ * returns the VM's per-boot host key; who may ask is the caller's decision.
140
+ */
141
+ sshCertificate(input: {
142
+ publicKey: string;
143
+ keyId: string;
144
+ }): Promise<OnBoxVmSshCertificate>;
123
145
  fetchPort(port: number, input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
124
146
  /**
125
147
  * A guest port, reached through the host service: the VM has no address
package/dist/on-box-vm.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { computerSizeSchema } from "./computer-backends.js";
3
3
  import * as Data from "effect/Data";
4
+ import * as Option from "effect/Option";
5
+ import * as Schema from "effect/Schema";
4
6
  import { SeamReplayPartitions, importSeamSigner, importSeamVerifiers, seamBodyDigest, seamHeader, signSeamRequest, unsignedPayload, verifySeamRequest, } from "@fungi.computer/seam";
5
7
  function accessHeaders(env) {
6
8
  const id = env.COMPUTER_VM_ACCESS_CLIENT_ID;
@@ -43,11 +45,19 @@ export function onBoxVmPlacement(env, hostId) {
43
45
  export class OnBoxVmUnavailableError extends Error {
44
46
  operation;
45
47
  status;
46
- constructor(operation, status, detail = "") {
48
+ detail;
49
+ /** The host's typed refusal, such as `scratch_capacity`; null when it names none. */
50
+ hostCode;
51
+ constructor(operation, status,
52
+ /** The host's own words, up to 200 characters. */
53
+ detail = "") {
47
54
  super(`On-box Computer VM ${operation} failed with HTTP ${String(status)}${detail ? `: ${detail}` : ""}`);
48
55
  this.operation = operation;
49
56
  this.status = status;
57
+ this.detail = detail;
50
58
  this.name = "OnBoxVmUnavailableError";
59
+ const body = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({ code: Schema.String })))(detail);
60
+ this.hostCode = Option.isSome(body) ? body.value.code : null;
51
61
  }
52
62
  }
53
63
  const signers = new Map();
@@ -97,6 +107,12 @@ const vmInventorySchema = z.array(vmStateSchema.extend({
97
107
  const vmStartSchema = z.lazy(() => z.strictObject({
98
108
  runtimeId: z.string().min(1).max(128),
99
109
  }));
110
+ /** vmd's signed answer: a user certificate for this VM and its per-boot host key. */
111
+ const vmSshCertificateSchema = z.strictObject({
112
+ certificate: z.string().min(1).max(4_096),
113
+ serial: z.string().regex(/^\d{1,20}$/u),
114
+ hostKey: z.string().min(1).max(1_024),
115
+ });
100
116
  /**
101
117
  * vmd's own traffic timer is only a backstop at its maximum: ComputerDO owns
102
118
  * idle sleep, so a kept-awake VM is not stopped by the host while it is quiet.
@@ -159,7 +175,7 @@ export class OnBoxVmContainerHost {
159
175
  signal,
160
176
  });
161
177
  if (!response.ok) {
162
- const detail = (await response.text()).slice(0, 200);
178
+ const detail = (await response.text()).slice(0, 400);
163
179
  throw new OnBoxVmUnavailableError(operation, response.status, detail);
164
180
  }
165
181
  return schema.parse(await response.json());
@@ -226,6 +242,17 @@ export class OnBoxVmContainerHost {
226
242
  workspace,
227
243
  });
228
244
  }
245
+ /**
246
+ * Ask the host to sign `publicKey` for this VM's guest sshd. The host signs
247
+ * only this signed control request, names this VM as the one principal and
248
+ * returns the VM's per-boot host key; who may ask is the caller's decision.
249
+ */
250
+ sshCertificate(input) {
251
+ return this.#call("ssh-certificate", vmSshCertificateSchema, {
252
+ publicKey: input.publicKey,
253
+ keyId: input.keyId,
254
+ });
255
+ }
229
256
  fetchPort(port, input, init) {
230
257
  return this.port(port).fetch(input, init);
231
258
  }