@fungi.computer/computer 0.13.0 → 0.14.1
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 +1 -1
- package/container/computer-init.mjs +20 -3
- package/container/computer-start.sh +2 -1
- package/container/runtime-privileges.cc +6 -4
- package/container/runtime-privileges.mjs +21 -2
- package/dist/computerd.cjs +76 -17
- package/dist/index.js +3 -9
- package/dist/port-access.d.ts +39 -0
- package/dist/port-access.js +246 -0
- package/dist/process-inventory.js +2 -0
- package/package.json +15 -9
package/Dockerfile
CHANGED
|
@@ -38,7 +38,7 @@ 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 tini \
|
|
41
|
+
fuse3 libfuse2t64 ca-certificates curl git procps tini \
|
|
42
42
|
&& rm -rf /var/lib/apt/lists/*
|
|
43
43
|
|
|
44
44
|
RUN npm install --global --no-fund --no-audit pnpm@11.24.0 \
|
|
@@ -6,7 +6,10 @@ import { spawn } from "node:child_process";
|
|
|
6
6
|
import process from "node:process";
|
|
7
7
|
import { setTimeout, clearTimeout } from "node:timers";
|
|
8
8
|
import { fileURLToPath, URL } from "node:url";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
enterRuntimePhase,
|
|
11
|
+
readRuntimePrivilegeMode,
|
|
12
|
+
} from "./runtime-privileges.mjs";
|
|
10
13
|
import { boundedRuntimeMs } from "./resource-bounds.mjs";
|
|
11
14
|
|
|
12
15
|
const computerd = "/opt/fungi/computerd.cjs";
|
|
@@ -25,6 +28,20 @@ function log(message, fields) {
|
|
|
25
28
|
);
|
|
26
29
|
}
|
|
27
30
|
|
|
31
|
+
// The maintained Debian service detaches dockerd. Its failure must not stop
|
|
32
|
+
// the Computer; a user can recover it with sudo service docker restart.
|
|
33
|
+
if (readRuntimePrivilegeMode() === "vm-sudo") {
|
|
34
|
+
const docker = spawn("/usr/sbin/service", ["docker", "start"], {
|
|
35
|
+
stdio: ["ignore", "inherit", "inherit"],
|
|
36
|
+
});
|
|
37
|
+
docker.once("error", (error) =>
|
|
38
|
+
log("Docker service failed to start", { error: error.message }),
|
|
39
|
+
);
|
|
40
|
+
docker.once("exit", (code) => {
|
|
41
|
+
if (code !== 0) log("Docker service failed to start", { code });
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
28
45
|
let terminal;
|
|
29
46
|
const daemon = spawn(process.execPath, [computerd], {
|
|
30
47
|
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
|
@@ -80,8 +97,8 @@ try {
|
|
|
80
97
|
});
|
|
81
98
|
});
|
|
82
99
|
enterRuntimePhase();
|
|
83
|
-
// exec the terminal runtime with the permanent UID/GID and
|
|
84
|
-
// inherited. The mount daemon retains its live FUSE descriptor and VFS state.
|
|
100
|
+
// exec the terminal runtime with the permanent UID/GID and the image
|
|
101
|
+
// privilege mode inherited. The mount daemon retains its live FUSE descriptor and VFS state.
|
|
85
102
|
terminal = spawn(process.execPath, ["/opt/fungi/terminal-runtime.mjs"], {
|
|
86
103
|
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
|
87
104
|
env: process.env,
|
|
@@ -12,7 +12,8 @@ else
|
|
|
12
12
|
printf '%s\n' "$uid" >"$uid_file"
|
|
13
13
|
fi
|
|
14
14
|
if ! getent passwd "$uid" >/dev/null; then
|
|
15
|
-
|
|
15
|
+
groupadd --gid "$uid" fungi
|
|
16
|
+
useradd --no-log-init --uid "$uid" --gid "$uid" --no-create-home --home-dir /workspace --shell /bin/bash fungi
|
|
16
17
|
fi
|
|
17
18
|
export COMPUTER_RUNTIME_UID="$uid"
|
|
18
19
|
pids_max=$(node --input-type=module -e 'import { computerResourceBounds } from "/opt/fungi/resource-bounds.mjs"; process.stdout.write(String(computerResourceBounds.pidsMax))')
|
|
@@ -8,16 +8,18 @@
|
|
|
8
8
|
// This runs only after FUSE is mounted and before any runtime listener opens.
|
|
9
9
|
// libc's credential calls update every thread, including FUSE's worker threads.
|
|
10
10
|
static napi_value enterRuntimePhase(napi_env env, napi_callback_info info) {
|
|
11
|
-
size_t count =
|
|
12
|
-
napi_value args[
|
|
11
|
+
size_t count = 2;
|
|
12
|
+
napi_value args[2];
|
|
13
|
+
bool no_new_privs;
|
|
13
14
|
uint32_t uid;
|
|
14
15
|
if (napi_get_cb_info(env, info, &count, args, nullptr, nullptr) != napi_ok ||
|
|
15
|
-
count !=
|
|
16
|
+
count != 2 ||
|
|
17
|
+
napi_get_value_bool(env, args[1], &no_new_privs) != napi_ok || napi_get_value_uint32(env, args[0], &uid) != napi_ok ||
|
|
16
18
|
uid < 100000 || uid > 2000099999 || getuid() != 0) {
|
|
17
19
|
napi_throw_error(env, nullptr, "Invalid privileged mount transition");
|
|
18
20
|
return nullptr;
|
|
19
21
|
}
|
|
20
|
-
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 ||
|
|
22
|
+
if ((no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) ||
|
|
21
23
|
setgroups(0, nullptr) != 0 || setresgid(uid, uid, uid) != 0 ||
|
|
22
24
|
setresuid(uid, uid, uid) != 0) {
|
|
23
25
|
napi_throw_error(env, nullptr, strerror(errno));
|
|
@@ -1,11 +1,30 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
1
2
|
import process from "node:process";
|
|
2
3
|
import { createRequire } from "node:module";
|
|
3
4
|
const loadNative = createRequire(import.meta.url);
|
|
4
|
-
|
|
5
|
+
|
|
6
|
+
/** @returns {"contained" | "vm-sudo"} */
|
|
7
|
+
export function readRuntimePrivilegeMode(
|
|
8
|
+
marker = "/etc/fungi/runtime-privilege-mode",
|
|
9
|
+
) {
|
|
10
|
+
let mode;
|
|
11
|
+
try {
|
|
12
|
+
mode = readFileSync(marker, "utf8").trim();
|
|
13
|
+
} catch (error) {
|
|
14
|
+
if (error.code === "ENOENT") return "contained";
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
if (mode !== "contained" && mode !== "vm-sudo")
|
|
18
|
+
throw new Error("Invalid Computer runtime privilege mode");
|
|
19
|
+
return mode;
|
|
20
|
+
}
|
|
5
21
|
|
|
6
22
|
export function enterRuntimePhase() {
|
|
7
23
|
const uid = Number(process.env.COMPUTER_RUNTIME_UID);
|
|
8
24
|
if (!Number.isSafeInteger(uid) || uid < 100_000 || uid > 2_000_099_999)
|
|
9
25
|
throw new Error("Invalid Computer runtime UID");
|
|
10
|
-
|
|
26
|
+
loadNative("./runtime-privileges.node").enterRuntimePhase(
|
|
27
|
+
uid,
|
|
28
|
+
readRuntimePrivilegeMode() === "contained",
|
|
29
|
+
);
|
|
11
30
|
}
|
package/dist/computerd.cjs
CHANGED
|
@@ -15788,7 +15788,9 @@ var DEFAULTS = {
|
|
|
15788
15788
|
defaultTimeoutMs: 32e4,
|
|
15789
15789
|
// After SIGTERM, give the child this long to exit on its own
|
|
15790
15790
|
// before sending SIGKILL.
|
|
15791
|
-
killGraceMs: 5e3
|
|
15791
|
+
killGraceMs: 5e3,
|
|
15792
|
+
// After the shell exits, how long to wait for its output pipes to end.
|
|
15793
|
+
pipeDrainGraceMs: 250
|
|
15792
15794
|
};
|
|
15793
15795
|
function signalGroup(child, signal) {
|
|
15794
15796
|
if (child.pid === void 0) return;
|
|
@@ -15799,10 +15801,42 @@ function signalGroup(child, signal) {
|
|
|
15799
15801
|
throw err;
|
|
15800
15802
|
}
|
|
15801
15803
|
}
|
|
15804
|
+
var terminating = /* @__PURE__ */ new Set([
|
|
15805
|
+
"SIGTERM",
|
|
15806
|
+
"SIGINT",
|
|
15807
|
+
"SIGHUP",
|
|
15808
|
+
"SIGQUIT"
|
|
15809
|
+
]);
|
|
15810
|
+
var pkillMissing = false;
|
|
15811
|
+
function signalSession(child, signal) {
|
|
15812
|
+
if (child.pid === void 0 || pkillMissing) return;
|
|
15813
|
+
(0, import_node_child_process.execFile)(
|
|
15814
|
+
"pkill",
|
|
15815
|
+
[`-${signal.slice(3)}`, "-s", String(child.pid)],
|
|
15816
|
+
{ timeout: 5e3 },
|
|
15817
|
+
(err) => {
|
|
15818
|
+
if (err === null || "code" in err && err.code === 1) return;
|
|
15819
|
+
if ("code" in err && err.code === "ENOENT") {
|
|
15820
|
+
pkillMissing = true;
|
|
15821
|
+
console.error(
|
|
15822
|
+
"computerd: pkill is not installed; Stop signals only the command's process group"
|
|
15823
|
+
);
|
|
15824
|
+
return;
|
|
15825
|
+
}
|
|
15826
|
+
console.error(`computerd: pkill failed: ${err.message}`);
|
|
15827
|
+
}
|
|
15828
|
+
);
|
|
15829
|
+
}
|
|
15830
|
+
function signalTree(child, signal) {
|
|
15831
|
+
signalGroup(child, signal);
|
|
15832
|
+
signalSession(child, signal);
|
|
15833
|
+
}
|
|
15802
15834
|
var Runner = class {
|
|
15803
15835
|
db;
|
|
15804
15836
|
opts;
|
|
15805
15837
|
records = /* @__PURE__ */ new Map();
|
|
15838
|
+
/** SIGKILL back-ups for stopped commands; they outlive the command's shell. */
|
|
15839
|
+
backups = /* @__PURE__ */ new Set();
|
|
15806
15840
|
sweepTimer;
|
|
15807
15841
|
disposed = false;
|
|
15808
15842
|
constructor(init) {
|
|
@@ -15861,6 +15895,7 @@ var Runner = class {
|
|
|
15861
15895
|
};
|
|
15862
15896
|
this.records.set(id, record);
|
|
15863
15897
|
const onData = (name) => (chunk) => {
|
|
15898
|
+
if (!record.live) return;
|
|
15864
15899
|
const value = new Uint8Array(chunk);
|
|
15865
15900
|
const seq = log.append(name, value);
|
|
15866
15901
|
record.lastOutputAt = this.opts.now();
|
|
@@ -15897,10 +15932,6 @@ var Runner = class {
|
|
|
15897
15932
|
clearTimeout(record.timeoutTimer);
|
|
15898
15933
|
record.timeoutTimer = void 0;
|
|
15899
15934
|
}
|
|
15900
|
-
if (record.killTimer !== void 0) {
|
|
15901
|
-
clearTimeout(record.killTimer);
|
|
15902
|
-
record.killTimer = void 0;
|
|
15903
|
-
}
|
|
15904
15935
|
if (record.heartbeatTimer !== void 0) {
|
|
15905
15936
|
clearTimeout(record.heartbeatTimer);
|
|
15906
15937
|
record.heartbeatTimer = void 0;
|
|
@@ -15922,7 +15953,22 @@ var Runner = class {
|
|
|
15922
15953
|
record.subscriber = void 0;
|
|
15923
15954
|
this.scheduleSweep();
|
|
15924
15955
|
};
|
|
15925
|
-
child.once("exit",
|
|
15956
|
+
child.once("exit", (code, signal) => {
|
|
15957
|
+
let settled = false;
|
|
15958
|
+
const settle = () => {
|
|
15959
|
+
if (settled) return;
|
|
15960
|
+
settled = true;
|
|
15961
|
+
clearTimeout(grace);
|
|
15962
|
+
child.stdout?.destroy();
|
|
15963
|
+
child.stderr?.destroy();
|
|
15964
|
+
finalise(code, signal);
|
|
15965
|
+
};
|
|
15966
|
+
child.stdout?.resume();
|
|
15967
|
+
child.stderr?.resume();
|
|
15968
|
+
const grace = setTimeout(settle, DEFAULTS.pipeDrainGraceMs);
|
|
15969
|
+
grace.unref?.();
|
|
15970
|
+
child.once("close", settle);
|
|
15971
|
+
});
|
|
15926
15972
|
child.once("error", (err) => {
|
|
15927
15973
|
if (!record.live) return;
|
|
15928
15974
|
const value = new TextEncoder().encode(`spawn failed: ${err.message}
|
|
@@ -15935,11 +15981,8 @@ var Runner = class {
|
|
|
15935
15981
|
if (timeoutMs > 0) {
|
|
15936
15982
|
record.timeoutTimer = setTimeout(() => {
|
|
15937
15983
|
if (!record.live) return;
|
|
15938
|
-
|
|
15939
|
-
|
|
15940
|
-
if (!record.live) return;
|
|
15941
|
-
signalGroup(child, "SIGKILL");
|
|
15942
|
-
}, DEFAULTS.killGraceMs);
|
|
15984
|
+
signalTree(child, "SIGTERM");
|
|
15985
|
+
this.backUpWithKill(child);
|
|
15943
15986
|
}, timeoutMs);
|
|
15944
15987
|
}
|
|
15945
15988
|
this.scheduleSweep();
|
|
@@ -15969,7 +16012,25 @@ var Runner = class {
|
|
|
15969
16012
|
throw new ExecError("ENOENT", `no exec record for id ${id}`);
|
|
15970
16013
|
}
|
|
15971
16014
|
if (!record.live) return;
|
|
15972
|
-
|
|
16015
|
+
signalTree(record.child, signal);
|
|
16016
|
+
if (terminating.has(signal)) this.backUpWithKill(record.child);
|
|
16017
|
+
}
|
|
16018
|
+
/**
|
|
16019
|
+
* After the grace, SIGKILL whatever still holds the command's group or
|
|
16020
|
+
* session. The shell usually exits on SIGTERM and finishes the record while
|
|
16021
|
+
* a server it started through timeout(1) keeps running, so this does not
|
|
16022
|
+
* wait on the record. If nothing of the session is left by then, the signal
|
|
16023
|
+
* finds no process; a pid reused for a new session leader inside the grace
|
|
16024
|
+
* is the one case it could reach, and the kernel does not reuse a pid while
|
|
16025
|
+
* any process still holds it as a group or session id.
|
|
16026
|
+
*/
|
|
16027
|
+
backUpWithKill(child) {
|
|
16028
|
+
const timer = setTimeout(() => {
|
|
16029
|
+
this.backups.delete(timer);
|
|
16030
|
+
signalTree(child, "SIGKILL");
|
|
16031
|
+
}, DEFAULTS.killGraceMs);
|
|
16032
|
+
timer.unref?.();
|
|
16033
|
+
this.backups.add(timer);
|
|
15973
16034
|
}
|
|
15974
16035
|
dispose(id) {
|
|
15975
16036
|
const record = this.records.get(id);
|
|
@@ -15985,6 +16046,8 @@ var Runner = class {
|
|
|
15985
16046
|
}
|
|
15986
16047
|
disposeAll() {
|
|
15987
16048
|
this.disposed = true;
|
|
16049
|
+
for (const timer of this.backups) clearTimeout(timer);
|
|
16050
|
+
this.backups.clear();
|
|
15988
16051
|
for (const record of [...this.records.values()]) {
|
|
15989
16052
|
this.disposeRecord(record);
|
|
15990
16053
|
}
|
|
@@ -16096,16 +16159,12 @@ var Runner = class {
|
|
|
16096
16159
|
clearTimeout(record.timeoutTimer);
|
|
16097
16160
|
record.timeoutTimer = void 0;
|
|
16098
16161
|
}
|
|
16099
|
-
if (record.killTimer !== void 0) {
|
|
16100
|
-
clearTimeout(record.killTimer);
|
|
16101
|
-
record.killTimer = void 0;
|
|
16102
|
-
}
|
|
16103
16162
|
if (record.heartbeatTimer !== void 0) {
|
|
16104
16163
|
clearTimeout(record.heartbeatTimer);
|
|
16105
16164
|
record.heartbeatTimer = void 0;
|
|
16106
16165
|
}
|
|
16107
16166
|
if (record.child.exitCode === null && record.child.signalCode === null) {
|
|
16108
|
-
|
|
16167
|
+
signalTree(record.child, "SIGKILL");
|
|
16109
16168
|
}
|
|
16110
16169
|
record.subscriber?.close();
|
|
16111
16170
|
record.subscriber = void 0;
|
package/dist/index.js
CHANGED
|
@@ -845,8 +845,6 @@ export class ComputerDO extends ContainerComputer {
|
|
|
845
845
|
});
|
|
846
846
|
if (!exposed)
|
|
847
847
|
return Response.json({ error: "port is not exposed" }, { status: 404 });
|
|
848
|
-
if (request.headers.has("upgrade"))
|
|
849
|
-
return Response.json({ error: "preview WebSocket upgrades are not supported" }, { status: 400 });
|
|
850
848
|
try {
|
|
851
849
|
const headers = new Headers(request.headers);
|
|
852
850
|
for (const name of [
|
|
@@ -874,13 +872,9 @@ export class ComputerDO extends ContainerComputer {
|
|
|
874
872
|
const response = await this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
|
|
875
873
|
.port(port)
|
|
876
874
|
.fetch(new Request(forwarded, { headers })));
|
|
877
|
-
const
|
|
878
|
-
|
|
879
|
-
return
|
|
880
|
-
status: response.status,
|
|
881
|
-
statusText: response.statusText,
|
|
882
|
-
headers: safeHeaders,
|
|
883
|
-
});
|
|
875
|
+
const safe = new Response(response.body, response);
|
|
876
|
+
safe.headers.delete("set-cookie");
|
|
877
|
+
return safe;
|
|
884
878
|
}
|
|
885
879
|
catch (cause) {
|
|
886
880
|
console.error("Computer runtime operation failed", cause);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
/** Admission is checked by the host before it issues a port credential. */
|
|
4
|
+
export type PortAccessPrincipal = Readonly<{
|
|
5
|
+
userId: string;
|
|
6
|
+
teamId: string;
|
|
7
|
+
}> | Readonly<{
|
|
8
|
+
ownerId: string;
|
|
9
|
+
}>;
|
|
10
|
+
/** Visibility belongs to an existing exposed port, never a second catalog. */
|
|
11
|
+
export type PortVisibility = "private" | "unlisted" | "public";
|
|
12
|
+
/** Refusal at the host's issuance or configuration boundary. */
|
|
13
|
+
export declare class PortAccessError extends Error {
|
|
14
|
+
readonly reason: "unexposed" | "public_disabled" | "not_unlisted" | "capacity";
|
|
15
|
+
constructor(reason: "unexposed" | "public_disabled" | "not_unlisted" | "capacity");
|
|
16
|
+
}
|
|
17
|
+
/** Additive migration: existing Oyster exposure rows remain private. */
|
|
18
|
+
export declare function initializePortAccess(storage: WatchdogSqliteOwner): void;
|
|
19
|
+
/** One Computer's port credentials; the host owns membership and routing. */
|
|
20
|
+
export declare class ComputerPortAccess {
|
|
21
|
+
private readonly storage;
|
|
22
|
+
private readonly options;
|
|
23
|
+
constructor(storage: WatchdogSqliteOwner, options?: Readonly<{
|
|
24
|
+
publicAccess?: "on";
|
|
25
|
+
now?: () => number;
|
|
26
|
+
}>);
|
|
27
|
+
private now;
|
|
28
|
+
private visibility;
|
|
29
|
+
/** Returns a new share secret only when entering unlisted visibility. */
|
|
30
|
+
setVisibility(portInput: number, input: PortVisibility): Promise<string | null>;
|
|
31
|
+
/** Rotation revokes outstanding tokens and sessions in the same transaction. */
|
|
32
|
+
resetShare(portInput: number): Promise<string>;
|
|
33
|
+
/** The host rechecks admission inside issuance, after asynchronous hashing. */
|
|
34
|
+
issue(portInput: number, input: PortAccessPrincipal, accept: () => void): Promise<string>;
|
|
35
|
+
private exchange;
|
|
36
|
+
private admits;
|
|
37
|
+
/** Mount on one target host. Forwarding remains responsible for live exposure. */
|
|
38
|
+
gate(portInput: number, entryUrl: string, forward: (request: Request) => Response | Promise<Response>): Hono;
|
|
39
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { LONG, nanoid } from "@fungi.computer/cairn";
|
|
2
|
+
import { computerPortSchema } from "@fungi.computer/computer-contract";
|
|
3
|
+
import { Hono } from "hono";
|
|
4
|
+
import { getCookie, setCookie } from "hono/cookie";
|
|
5
|
+
import { html } from "hono/html";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
const visibilitySchema = z.enum(["private", "unlisted", "public"]);
|
|
8
|
+
const principalSchema = z.union([
|
|
9
|
+
z.strictObject({ userId: z.string().min(1), teamId: z.string().min(1) }),
|
|
10
|
+
z.strictObject({ ownerId: z.string().min(1) }),
|
|
11
|
+
]);
|
|
12
|
+
const credentialSchema = z
|
|
13
|
+
.string()
|
|
14
|
+
.length(LONG)
|
|
15
|
+
.regex(/^[a-z0-9]+$/);
|
|
16
|
+
const tokenLifetimeMs = 300_000;
|
|
17
|
+
const sessionLifetimeMs = 3_600_000;
|
|
18
|
+
const maximumPendingTokens = 64;
|
|
19
|
+
/** Refusal at the host's issuance or configuration boundary. */
|
|
20
|
+
export class PortAccessError extends Error {
|
|
21
|
+
reason;
|
|
22
|
+
constructor(reason) {
|
|
23
|
+
super(`Port access: ${reason}`);
|
|
24
|
+
this.reason = reason;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Additive migration: existing Oyster exposure rows remain private. */
|
|
28
|
+
export function initializePortAccess(storage) {
|
|
29
|
+
storage.transactionSync(() => {
|
|
30
|
+
const columns = storage.sql
|
|
31
|
+
.exec("PRAGMA table_info(computer_exposed_ports)")
|
|
32
|
+
.toArray();
|
|
33
|
+
if (!columns.some((column) => column.name === "visibility"))
|
|
34
|
+
storage.sql.exec("ALTER TABLE computer_exposed_ports ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private' CHECK (visibility IN ('private','unlisted','public'))");
|
|
35
|
+
if (!columns.some((column) => column.name === "share_token_hash"))
|
|
36
|
+
storage.sql.exec("ALTER TABLE computer_exposed_ports ADD COLUMN share_token_hash TEXT");
|
|
37
|
+
storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_port_connect (token_hash TEXT PRIMARY KEY, port INTEGER NOT NULL, principal_json TEXT NOT NULL, expires_at INTEGER NOT NULL) STRICT");
|
|
38
|
+
storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_port_session (session_hash TEXT PRIMARY KEY, port INTEGER NOT NULL, principal_json TEXT, kind TEXT NOT NULL CHECK (kind IN ('member','share')), expires_at INTEGER NOT NULL) STRICT");
|
|
39
|
+
// Every removal path (unexpose, process exit, idle sleep) revokes in the
|
|
40
|
+
// same SQLite transaction, including a remove followed by re-exposure.
|
|
41
|
+
storage.sql.exec("CREATE TRIGGER IF NOT EXISTS computer_port_access_deleted AFTER DELETE ON computer_exposed_ports BEGIN DELETE FROM computer_port_connect WHERE port = OLD.port; DELETE FROM computer_port_session WHERE port = OLD.port; END");
|
|
42
|
+
storage.sql.exec("CREATE TRIGGER IF NOT EXISTS computer_port_access_changed AFTER UPDATE OF visibility, share_token_hash ON computer_exposed_ports WHEN OLD.visibility IS NOT NEW.visibility OR OLD.share_token_hash IS NOT NEW.share_token_hash BEGIN DELETE FROM computer_port_connect WHERE port = OLD.port; DELETE FROM computer_port_session WHERE port = OLD.port; END");
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
async function hash(value) {
|
|
46
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
47
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
48
|
+
}
|
|
49
|
+
/** One Computer's port credentials; the host owns membership and routing. */
|
|
50
|
+
export class ComputerPortAccess {
|
|
51
|
+
storage;
|
|
52
|
+
options;
|
|
53
|
+
constructor(storage, options = {}) {
|
|
54
|
+
this.storage = storage;
|
|
55
|
+
this.options = options;
|
|
56
|
+
initializePortAccess(storage);
|
|
57
|
+
}
|
|
58
|
+
now() {
|
|
59
|
+
return this.options.now?.() ?? Date.now();
|
|
60
|
+
}
|
|
61
|
+
visibility(port) {
|
|
62
|
+
const row = this.storage.sql
|
|
63
|
+
.exec("SELECT visibility FROM computer_exposed_ports WHERE port = ?", port)
|
|
64
|
+
.toArray()[0];
|
|
65
|
+
return row === undefined
|
|
66
|
+
? undefined
|
|
67
|
+
: visibilitySchema.parse(row.visibility);
|
|
68
|
+
}
|
|
69
|
+
/** Returns a new share secret only when entering unlisted visibility. */
|
|
70
|
+
async setVisibility(portInput, input) {
|
|
71
|
+
const port = computerPortSchema.parse(portInput);
|
|
72
|
+
const visibility = visibilitySchema.parse(input);
|
|
73
|
+
if (visibility === "public" && this.options.publicAccess !== "on")
|
|
74
|
+
throw new PortAccessError("public_disabled");
|
|
75
|
+
const share = visibility === "unlisted" ? nanoid(LONG) : null;
|
|
76
|
+
const shareHash = share === null ? null : await hash(share);
|
|
77
|
+
return this.storage.transactionSync(() => {
|
|
78
|
+
const previous = this.visibility(port);
|
|
79
|
+
if (previous === undefined)
|
|
80
|
+
throw new PortAccessError("unexposed");
|
|
81
|
+
if (previous === visibility)
|
|
82
|
+
return null;
|
|
83
|
+
this.storage.sql.exec("UPDATE computer_exposed_ports SET visibility = ?, share_token_hash = ? WHERE port = ?", visibility, shareHash, port);
|
|
84
|
+
return share;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** Rotation revokes outstanding tokens and sessions in the same transaction. */
|
|
88
|
+
async resetShare(portInput) {
|
|
89
|
+
const port = computerPortSchema.parse(portInput);
|
|
90
|
+
const secret = nanoid(LONG);
|
|
91
|
+
const secretHash = await hash(secret);
|
|
92
|
+
return this.storage.transactionSync(() => {
|
|
93
|
+
if (this.visibility(port) !== "unlisted")
|
|
94
|
+
throw new PortAccessError("not_unlisted");
|
|
95
|
+
this.storage.sql.exec("UPDATE computer_exposed_ports SET share_token_hash = ? WHERE port = ?", secretHash, port);
|
|
96
|
+
return secret;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/** The host rechecks admission inside issuance, after asynchronous hashing. */
|
|
100
|
+
async issue(portInput, input, accept) {
|
|
101
|
+
const port = computerPortSchema.parse(portInput);
|
|
102
|
+
const principal = principalSchema.parse(input);
|
|
103
|
+
const token = nanoid(LONG);
|
|
104
|
+
const tokenHash = await hash(token);
|
|
105
|
+
return this.storage.transactionSync(() => {
|
|
106
|
+
accept();
|
|
107
|
+
if (this.visibility(port) === undefined)
|
|
108
|
+
throw new PortAccessError("unexposed");
|
|
109
|
+
const now = this.now();
|
|
110
|
+
this.storage.sql.exec("DELETE FROM computer_port_connect WHERE expires_at <= ?", now);
|
|
111
|
+
const count = z
|
|
112
|
+
.number()
|
|
113
|
+
.int()
|
|
114
|
+
.nonnegative()
|
|
115
|
+
.parse(this.storage.sql
|
|
116
|
+
.exec("SELECT COUNT(*) AS count FROM computer_port_connect")
|
|
117
|
+
.toArray()[0]?.count);
|
|
118
|
+
if (count >= maximumPendingTokens)
|
|
119
|
+
throw new PortAccessError("capacity");
|
|
120
|
+
this.storage.sql.exec("INSERT INTO computer_port_connect VALUES (?, ?, ?, ?)", tokenHash, port, JSON.stringify(principal), now + tokenLifetimeMs);
|
|
121
|
+
return token;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
async exchange(port, secret, kind) {
|
|
125
|
+
if (!credentialSchema.safeParse(secret).success)
|
|
126
|
+
return null;
|
|
127
|
+
const secretHash = await hash(secret);
|
|
128
|
+
const session = nanoid(LONG);
|
|
129
|
+
const sessionHash = await hash(session);
|
|
130
|
+
return this.storage.transactionSync(() => {
|
|
131
|
+
const visibility = this.visibility(port);
|
|
132
|
+
if (visibility === undefined ||
|
|
133
|
+
(visibility === "public" && this.options.publicAccess !== "on"))
|
|
134
|
+
return null;
|
|
135
|
+
const now = this.now();
|
|
136
|
+
let principal = null;
|
|
137
|
+
if (kind === "member") {
|
|
138
|
+
const row = this.storage.sql
|
|
139
|
+
.exec("DELETE FROM computer_port_connect WHERE token_hash = ? AND port = ? AND expires_at > ? RETURNING principal_json", secretHash, port, now)
|
|
140
|
+
.toArray()[0];
|
|
141
|
+
if (row === undefined)
|
|
142
|
+
return null;
|
|
143
|
+
principal = JSON.stringify(principalSchema.parse(JSON.parse(z.string().parse(row.principal_json))));
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
if (visibility !== "unlisted")
|
|
147
|
+
return null;
|
|
148
|
+
const row = this.storage.sql
|
|
149
|
+
.exec("SELECT port FROM computer_exposed_ports WHERE port = ? AND share_token_hash = ?", port, secretHash)
|
|
150
|
+
.toArray()[0];
|
|
151
|
+
if (row === undefined)
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
this.storage.sql.exec("DELETE FROM computer_port_session WHERE expires_at <= ?", now);
|
|
155
|
+
this.storage.sql.exec("INSERT INTO computer_port_session VALUES (?, ?, ?, ?, ?)", sessionHash, port, principal, kind, now + sessionLifetimeMs);
|
|
156
|
+
return session;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
async admits(port, secret) {
|
|
160
|
+
if (secret === undefined || !credentialSchema.safeParse(secret).success)
|
|
161
|
+
return false;
|
|
162
|
+
const sessionHash = await hash(secret);
|
|
163
|
+
return (this.storage.sql
|
|
164
|
+
.exec("SELECT s.port FROM computer_port_session s JOIN computer_exposed_ports p ON p.port = s.port WHERE s.session_hash = ? AND s.port = ? AND s.expires_at > ? AND (p.visibility = 'unlisted' OR (p.visibility = 'private' AND s.kind = 'member'))", sessionHash, port, this.now())
|
|
165
|
+
.toArray().length === 1);
|
|
166
|
+
}
|
|
167
|
+
/** Mount on one target host. Forwarding remains responsible for live exposure. */
|
|
168
|
+
gate(portInput, entryUrl, forward) {
|
|
169
|
+
const port = computerPortSchema.parse(portInput);
|
|
170
|
+
const app = new Hono();
|
|
171
|
+
app.all("*", async (c) => {
|
|
172
|
+
c.header("Cache-Control", "no-store");
|
|
173
|
+
const denied = () => c.req.header("sec-fetch-dest") === "document"
|
|
174
|
+
? c.html(html `<!doctype html><title>Open this from Fungi</title>
|
|
175
|
+
<main>
|
|
176
|
+
<h1>Open this from Fungi</h1>
|
|
177
|
+
<a href="${entryUrl}">Open in Fungi</a>
|
|
178
|
+
</main>`, 401)
|
|
179
|
+
: c.body(null, 401);
|
|
180
|
+
// Sibling preview hosts are same-site but must never use each other's
|
|
181
|
+
// cookies. WebSockets bypass CORS, so require their exact origin too.
|
|
182
|
+
const upgrade = c.req.raw.headers.has("upgrade");
|
|
183
|
+
if (c.req.header("sec-fetch-site") === "same-site" ||
|
|
184
|
+
(upgrade && c.req.header("origin") !== new URL(c.req.url).origin))
|
|
185
|
+
return denied();
|
|
186
|
+
const visibility = this.visibility(port);
|
|
187
|
+
if (visibility === undefined ||
|
|
188
|
+
(visibility === "public" && this.options.publicAccess !== "on"))
|
|
189
|
+
return denied();
|
|
190
|
+
if (visibility !== "public") {
|
|
191
|
+
const token = c.req.query("token");
|
|
192
|
+
const share = c.req.query("t");
|
|
193
|
+
const parameter = token !== undefined
|
|
194
|
+
? "token"
|
|
195
|
+
: share !== undefined && visibility === "unlisted"
|
|
196
|
+
? "t"
|
|
197
|
+
: null;
|
|
198
|
+
// Vite owns its WebSocket token query; upgrades use an existing session.
|
|
199
|
+
if (parameter !== null && !upgrade) {
|
|
200
|
+
const session = await this.exchange(port, (parameter === "token" ? token : share) ?? "", parameter === "token" ? "member" : "share");
|
|
201
|
+
if (session === null)
|
|
202
|
+
return denied();
|
|
203
|
+
setCookie(c, "fungi-port", session, {
|
|
204
|
+
prefix: "host",
|
|
205
|
+
httpOnly: true,
|
|
206
|
+
secure: true,
|
|
207
|
+
sameSite: "Lax",
|
|
208
|
+
path: "/",
|
|
209
|
+
maxAge: 3600,
|
|
210
|
+
});
|
|
211
|
+
const target = new URL(c.req.url);
|
|
212
|
+
target.searchParams.delete(parameter);
|
|
213
|
+
c.header("Referrer-Policy", "no-referrer");
|
|
214
|
+
return c.redirect(target.toString(), 302);
|
|
215
|
+
}
|
|
216
|
+
if (!(await this.admits(port, getCookie(c, "fungi-port", "host"))))
|
|
217
|
+
return denied();
|
|
218
|
+
}
|
|
219
|
+
const headers = new Headers(c.req.raw.headers);
|
|
220
|
+
for (const name of [
|
|
221
|
+
"authorization",
|
|
222
|
+
"cookie",
|
|
223
|
+
"proxy-authorization",
|
|
224
|
+
"cf-access-jwt-assertion",
|
|
225
|
+
"cf-access-client-id",
|
|
226
|
+
"cf-access-client-secret",
|
|
227
|
+
"cf-access-authenticated-user-email",
|
|
228
|
+
"x-authenticated-user",
|
|
229
|
+
"x-authenticated-email",
|
|
230
|
+
"x-auth-request-user",
|
|
231
|
+
"x-auth-request-email",
|
|
232
|
+
"x-user-id",
|
|
233
|
+
"x-user-email",
|
|
234
|
+
"x-forwarded-user",
|
|
235
|
+
"x-forwarded-email",
|
|
236
|
+
])
|
|
237
|
+
headers.delete(name);
|
|
238
|
+
const response = await forward(new Request(c.req.raw, { headers }));
|
|
239
|
+
const safe = new Response(response.body, response);
|
|
240
|
+
safe.headers.delete("set-cookie");
|
|
241
|
+
safe.headers.set("Cache-Control", "no-store");
|
|
242
|
+
return safe;
|
|
243
|
+
});
|
|
244
|
+
return app;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -53,6 +53,7 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
|
|
|
53
53
|
import { z } from "zod";
|
|
54
54
|
import { computerProcessSchema, processStartInputSchema, mintComputerProcessId, ComputerProcessLimitError, ComputerPortReservedError, ComputerPortConflictError, ComputerPortLimitError, isComputerReservedPort, maximumExposedPorts, maximumProcessLogLineCharacters, maximumProcessLogLines, maximumProcessRecords, maximumRunningProcesses, } from "@fungi.computer/computer-contract";
|
|
55
55
|
import { ComputerOperationConflictError } from "./operation-record.js";
|
|
56
|
+
import { initializePortAccess } from "./port-access.js";
|
|
56
57
|
function toProcess(row) {
|
|
57
58
|
return computerProcessSchema.parse({
|
|
58
59
|
id: row.id,
|
|
@@ -161,6 +162,7 @@ export class ComputerProcessInventory {
|
|
|
161
162
|
}
|
|
162
163
|
storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_processes (id TEXT PRIMARY KEY, request_scope TEXT NOT NULL, request_id TEXT NOT NULL, input_hash TEXT NOT NULL, backend TEXT NOT NULL, command TEXT NOT NULL, cwd TEXT, port INTEGER, state TEXT NOT NULL CHECK (state IN ('running','exited')), exit_code INTEGER, sync TEXT NOT NULL DEFAULT 'unknown' CHECK (sync IN ('synced','pending','unknown')), started_at INTEGER NOT NULL, ended_at INTEGER, ended_reason TEXT CHECK (ended_reason IN ('idle-sleep')), log_tail TEXT NOT NULL DEFAULT '', log_truncated INTEGER NOT NULL DEFAULT 0, CHECK ((state = 'running') = (ended_at IS NULL)), UNIQUE(request_scope, request_id)) STRICT");
|
|
163
164
|
storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_exposed_ports (port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535), process_id TEXT) STRICT");
|
|
165
|
+
initializePortAccess(storage);
|
|
164
166
|
});
|
|
165
167
|
}
|
|
166
168
|
#matching(input, inputHash, accept) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fungi.computer/computer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.1",
|
|
4
4
|
"author": "Levi <levi@technomancy.dev>",
|
|
5
5
|
"description": "Cloudflare Computer host for one durable Fungi Computer",
|
|
6
6
|
"type": "module",
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"./egress": {
|
|
47
47
|
"types": "./dist/egress-policy.d.ts",
|
|
48
48
|
"import": "./dist/egress-policy.js"
|
|
49
|
+
},
|
|
50
|
+
"./port-access": {
|
|
51
|
+
"types": "./dist/port-access.d.ts",
|
|
52
|
+
"import": "./dist/port-access.js"
|
|
49
53
|
}
|
|
50
54
|
},
|
|
51
55
|
"files": [
|
|
@@ -59,14 +63,15 @@
|
|
|
59
63
|
"@fungi.computer/cairn": "0.1.0",
|
|
60
64
|
"@fungi.computer/capnweb": "0.12.0-fungi.0",
|
|
61
65
|
"@fungi.computer/cloudflare-computer": "0.2.1-fungi.2",
|
|
62
|
-
"@fungi.computer/cordyceps": "0.4.
|
|
63
|
-
"@fungi.computer/knapsack": "0.4.
|
|
64
|
-
"@fungi.computer/seam": "0.2.
|
|
65
|
-
"@fungi.computer/watchdog": "0.1.
|
|
66
|
-
"@fungi.computer/computer-contract": "0.5.
|
|
66
|
+
"@fungi.computer/cordyceps": "0.4.3",
|
|
67
|
+
"@fungi.computer/knapsack": "0.4.15",
|
|
68
|
+
"@fungi.computer/seam": "0.2.6",
|
|
69
|
+
"@fungi.computer/watchdog": "0.1.4",
|
|
70
|
+
"@fungi.computer/computer-contract": "0.5.2",
|
|
67
71
|
"effect": "4.0.2",
|
|
68
72
|
"just-bash": "3.4.2",
|
|
69
|
-
"zod": "4.4.3"
|
|
73
|
+
"zod": "4.4.3",
|
|
74
|
+
"hono": "4.13.5"
|
|
70
75
|
},
|
|
71
76
|
"devDependencies": {
|
|
72
77
|
"@cloudflare/workers-types": "5.20260828.1",
|
|
@@ -77,7 +82,8 @@
|
|
|
77
82
|
"tsx": "4.23.12",
|
|
78
83
|
"typescript": "5.9.3",
|
|
79
84
|
"uuid": "11.1.1",
|
|
80
|
-
"wrangler": "4.159.0"
|
|
85
|
+
"wrangler": "4.159.0",
|
|
86
|
+
"ws": "8.18.0"
|
|
81
87
|
},
|
|
82
88
|
"botanical": {
|
|
83
89
|
"role": "runtime",
|
|
@@ -119,7 +125,7 @@
|
|
|
119
125
|
"test:nightly": "bash ../../tooling/proof-runner/run-proof.sh node test/egress-proof.mjs",
|
|
120
126
|
"test:app-method-execution": "node test/app-method-execution-proof.mjs",
|
|
121
127
|
"test:execution-lifecycle": "node test/execution-lifecycle-proof.mjs",
|
|
122
|
-
"test:unit": "bash ../../tooling/proof-runner/hermetic-host.sh -- sh -c \"node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/egress-policy.test.mjs test/preview.test.mjs test/process-wait.test.mjs test/fleet.test.mjs test/proof-worker.test.mjs test/proof-client.test.mjs test/native-readiness.test.mjs test/workspace-sync.test.mjs test/runtime-observer.test.mjs test/files-patch.test.mjs test/exec-output.test.mjs && node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/seam-signature.test.mjs test/local-backend-replay.test.mjs test/machine-link-reopen-replay.test.mjs test/computer-backends.test.mjs test/terminal-welcome.test.mjs test/on-box-vm.test.mjs && node test/terminal-protocol.test.mjs && node test/container-policy.test.mjs && node test/files-adapter-proof.mjs && node test/operation-record-proof.mjs && node test/process-inventory-proof.mjs\"",
|
|
128
|
+
"test:unit": "bash ../../tooling/proof-runner/hermetic-host.sh -- sh -c \"node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/egress-policy.test.mjs test/preview.test.mjs test/port-access.test.mjs test/process-wait.test.mjs test/fleet.test.mjs test/proof-worker.test.mjs test/proof-client.test.mjs test/native-readiness.test.mjs test/workspace-sync.test.mjs test/runtime-observer.test.mjs test/files-patch.test.mjs test/exec-output.test.mjs && node --test --test-concurrency=${BOTANICAL_TEST_WORKERS:-4} test/seam-signature.test.mjs test/local-backend-replay.test.mjs test/machine-link-reopen-replay.test.mjs test/computer-backends.test.mjs test/terminal-welcome.test.mjs test/on-box-vm.test.mjs && node test/terminal-protocol.test.mjs && node test/container-policy.test.mjs && node test/files-adapter-proof.mjs && node test/operation-record-proof.mjs && node test/process-inventory-proof.mjs\"",
|
|
123
129
|
"test:fleet-native": "node test/fleet.native.mjs",
|
|
124
130
|
"assemble:image": "node scripts/assemble-image.mjs"
|
|
125
131
|
}
|