Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Own server: the box channel, with Ed25519 keys both ways, signed jobs for one box and yamux streams to the home
milind-sonibb5b7f3f458c
diff --git a/connector/e2e/run.sh b/connector/e2e/run.shindex c12d7ebef7..32853507b3 100644--- a/connector/e2e/run.sh+++ b/connector/e2e/run.sh@@ -70,18 +70,18 @@ control state >/dev/null || fail "the fake Admin did not start: $(cat "$OUT/admistep "install.sh with the code, as a person runs it"sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" "$CODE" | tee "$OUT/install.txt"-[ "$(tail -n 1 "$OUT/install.txt")" = "Connected. Your server shows up in MausBot in a minute." ] || fail "install.sh did not end connected"+[ "$(tail -n 1 "$OUT/install.txt")" = "Connected. Your server shows up in MausBot in a minute, for your team's Owner to accept." ] || fail "install.sh did not end connected"state=$(control state)expect '.connected and (.servers | length) == 1' "$state" "enrolled once"expect '.servers[0].host | .arch == "x86_64" and .apparmor and .userns and .cpus >= 2 and .diskGb >= 20 and (.docker | length) > 0' "$state" "enrolled with the host's facts"-expect '.servers[0].connector.protocol == 1 and .servers[0].connector.image == "mausbot-connector:e2e"' "$state" "enrolled with its identity"+expect '.servers[0].connector.protocol == 2 and .servers[0].connector.image == "mausbot-connector:e2e" and .servers[0].state == "pending"' "$state" "enrolled with its identity, waiting to be accepted"state_dir=/var/lib/docker/volumes/mausbot-connector/_data[ "$(sudo stat -c %a "$state_dir")" = 700 ] || fail "the connector's state folder is not root's alone"-[ "$(sudo stat -c %a "$state_dir/agent.json")" = 600 ] || fail "the agent token is not root's alone"+[ "$(sudo stat -c %a "$state_dir/agent.json")" = 600 ] || fail "the box key is not root's alone"step "running it again repairs and stays connected, without a new code"sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" | tee "$OUT/repair.txt"-[ "$(tail -n 1 "$OUT/repair.txt")" = "Connected. Your server shows up in MausBot in a minute." ] || fail "the repair did not end connected"+[ "$(tail -n 1 "$OUT/repair.txt")" = "Connected. Your server shows up in MausBot in a minute, for your team's Owner to accept." ] || fail "the repair did not end connected"expect '(.servers | length) == 1 and .connections >= 2 and .connected' "$(control state)" "the same server, connected again"step "a heartbeat with every check passing"@@ -97,6 +97,14 @@ ENV_JSON=$(jq -cn --arg secret "$SECRET" '{OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9", OMB_HIGHLEVEL_RELAY_URL: "off"}')+step "the team's Owner accepts the server; until then it takes no job that changes anything"+expect '.ok == false and .error.code == "pending_box"' "$(job stop '{}')" "a stop before the Owner accepted"+curl -sS --max-time 30 -X POST "$ADMIN/control/accept" >/dev/null+for _ in $(seq 1 30); do+ if docker exec mausbot-connector mausbot-connector status | jq -e '.accepted' >/dev/null; then break; fi+ sleep 1+done+step "start: the home runs with the bot box's settings, and the box passes every check"reply=$(job start "$(jq -cn --arg image "$HOME_A" --argjson env "$ENV_JSON" '{image: $image, env: $env}')" start-1)printf '%s\n' "$reply" >"$OUT/start.json"@@ -169,7 +177,7 @@ expect '.result.home.health.box.checks == "32/32"' "$status" "the box after thestep "nothing secret in the connector's log"docker logs mausbot-connector >"$OUT/connector.log" 2>&1if grep -qF "$SECRET" "$OUT/connector.log"; then fail "the bootstrap secret reached the connector's log"; fi-if grep -q "ombs_" "$OUT/connector.log"; then fail "the agent token reached the connector's log"; fi+if grep -qF "$(sudo jq -r .privateKey "$state_dir/agent.json")" "$OUT/connector.log"; then fail "the box's private key reached the connector's log"; fistep "uninstall stops everything and keeps the data; --delete-data deletes it"sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" uninstall | tee "$OUT/uninstall.txt"diff --git a/connector/install.sh b/connector/install.shindex 67ec14f994..5413d6f31d 100644--- a/connector/install.sh+++ b/connector/install.sh@@ -301,7 +301,7 @@ install_connector() {check_boxconnect "$code"say ""- say "Connected. Your server shows up in MausBot in a minute."+ say "Connected. Your server shows up in MausBot in a minute, for your team's Owner to accept."}# Removal never deletes the data, its safety copy or its backups unless --delete-data is typed.@@ -324,7 +324,7 @@ uninstall() {if command -v apparmor_parser >/dev/null 2>&1 && [ -f "$APPARMOR_DIR/$PROFILE" ]; then apparmor_parser -R "$APPARMOR_DIR/$PROFILE" >/dev/null 2>&1 || true; firm -f "$APPARMOR_DIR/$PROFILE" "$ETC_DIR/$SECCOMP"rmdir "$ETC_DIR" 2>/dev/null || true- # The connector's own state (its token, the home's settings) is not your data: MausBot hands both out again.+ # The connector's own state (its key, the home's settings) is not your data: a new code makes a new key.docker volume rm "$STATE_VOLUME" >/dev/null 2>&1 || trueif [ "$delete" = yes ]; thenfor volume in "$DATA_VOLUME" "$SNAPSHOT_VOLUME" $(docker volume ls -q --filter "label=$ROLE_LABEL=backup" 2>/dev/null); dodiff --git a/connector/src/agent.ts b/connector/src/agent.tsindex 4d82f3f6fe..86e6bbea94 100644--- a/connector/src/agent.ts+++ b/connector/src/agent.ts@@ -1,8 +1,19 @@-// The connector's one connection to the Admin: outbound, held open, re-opened with backoff. Jobs arrive on it and-// their replies go back on it, again on each new connection until the Admin acknowledges them.+// The connector's one connection to the Admin: outbound, held open, re-opened with backoff and jitter. Each connection+// starts with both sides proving their keys. Then the Admin's jobs arrive on it, each signed for this box, and their+// replies go back, again on each new connection until the Admin acknowledges them; the Admin's requests to the home+// arrive as yamux streams.+import { randomBytes } from "node:crypto";+import { errorText, type Log } from "./log.ts";-import { CLOSE_REPLACED, CLOSE_UNAUTHORIZED, CONNECT_PATH, HEARTBEAT_INTERVAL_MS, checkJob, type Heartbeat, type Job, type JobAck, type JobReply } from "./protocol.ts";-import type { StatusRecord } from "./state.ts";+import { MuxSession, type MuxStream } from "./mux.ts";+import {+ BOX_HEADER, CHANNEL_DEAD_MS, CHANNEL_PING_MS, CHANNEL_PROTOCOL, CLOSE_KEY_COPIED, CLOSE_PROTOCOL, CLOSE_REPLACED, CLOSE_SILENT,+ CLOSE_UNAUTHORIZED, CONNECT_PATH, HANDSHAKE_MS, HEARTBEAT_INTERVAL_MS, TRANSFER_SCHEME, TRANSFER_TOKEN_MS, authText, checkConfig, checkHello, checkJob,+ checkJobPayload, checkNonce, type Auth, type BoxState, type ConfigPayload, type Heartbeat, type Job, type JobAck, type JobErrorCode, type JobReply,+ type JobType, type TransferPayload,+} from "./protocol.ts";+import { b64u, seal, signText, unseal } from "./signed.ts";+import type { AgentRecord, ConfigRecord, StatusRecord } from "./state.ts";const MAX_MESSAGE_BYTES = 1024 * 1024;const KEPT_REPLIES = 200;@@ -10,11 +21,16 @@ const UNACKED_MAX_AGE_MS = 24 * 60 * 60_000;const STABLE_MS = 60_000;const UNAUTHORIZED_RETRY_MS = 5 * 60_000;const REPLACED_RETRY_MS = 60_000;+const RESTART_WAIT_MAX_MS = 5 * 60_000;+const DRAIN_POLL_MS = 50;+/** Jobs a box the team's Owner has not accepted yet still answers: they read, and carry none of the team's data. */+const READS: ReadonlySet<JobType> = new Set(["status", "host-health"]);export interface Socket {readonly readyState: number;readonly bufferedAmount: number;- send(data: string): void;+ binaryType: string;+ send(data: string | Uint8Array): void;close(code?: number, reason?: string): void;onopen: ((event: unknown) => void) | null;onmessage: ((event: { data: unknown }) => void) | null;@@ -22,24 +38,44 @@ export interface Socket {onerror: ((event: unknown) => void) | null;}-export type SocketFactory = (url: string, headers: Record<string, string>) => Socket;+export type SocketFactory = (url: string, init: { headers: Record<string, string>; protocols: string[] }) => Socket;/** Node's own WebSocket client (undici), which takes request headers. */-export const nodeSocket: SocketFactory = (url, headers) => new WebSocket(url, { headers }) as unknown as Socket;+export const nodeSocket: SocketFactory = (url, init) => new WebSocket(url, init as unknown as string[]) as unknown as Socket;++export interface Refusal {+ code: JobErrorCode;+ message: string;+ id?: string;+ type?: string;+}export interface AgentOptions {- admin: string;- token: string;+ /** This box's record, read at each use: the Admin's keys can change in a hello. */+ identity: () => AgentRecord;log: Log;socket?: SocketFactory;heartbeat: () => Promise<Heartbeat>;handle: (job: Job) => Promise<JobReply | null>;+ /** The next connection's count, already on the disk. */+ nextCount: () => number;+ /** A hello named new Admin keys: pin them. */+ saveAdminKeys?: (keys: Record<string, string>) => void;+ config?: { saved(): ConfigRecord | null; save(record: ConfigRecord): void };+ onConfig?: (config: ConfigPayload) => void;+ /** A stream the Admin opened: one request for the home. */+ stream?: (stream: MuxStream, accept: () => void) => void;+ /** A job refused before it ran; for the audit log. */+ refused?: (refusal: Refusal) => void;status?: (patch: Partial<StatusRecord>) => void;now?: () => number;random?: () => number;setTimer?: (callback: () => void, ms: number) => unknown;clearTimer?: (handle: unknown) => void;heartbeatMs?: number;+ pingMs?: number;+ deadMs?: number;+ handshakeMs?: number;}function isAck(message: unknown): message is JobAck {@@ -57,18 +93,43 @@ export function backoffMs(attempt: number, random: number): number {return Math.round(Math.min(60_000, 1000 * 2 ** Math.min(attempt, 6)) * (0.5 + random));}+const textOf = (data: unknown): string | null =>+ typeof data === "string" ? data : null;++const bytesOf = (data: unknown): Uint8Array | null =>+ data instanceof ArrayBuffer ? new Uint8Array(data) : ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null;++type Phase = "challenge" | "hello" | "open";++interface Connection {+ socket: Socket;+ phase: Phase;+ adminNonce: string;+ boxNonce: string;+ count: number;+ /** The Admin's clock minus this one's, from the hello. */+ offset: number;+ mux: MuxSession | null;+ heardAt: number;+ pings: number;+}+export class Agent {private readonly options: AgentOptions;private readonly now: () => number;private readonly random: () => number;private readonly setTimer: (callback: () => void, ms: number) => unknown;private readonly clearTimer: (handle: unknown) => void;- private socket: Socket | null = null;+ private connection: Connection | null = null;private attempt = 0;private openedAt = 0;private retry: unknown = null;private beat: unknown = null;+ private tick: unknown = null;+ private deadline: unknown = null;+ private restartIn: number | null = null;private stopped = true;+ private boxState: BoxState | null = null;/** Replies the Admin has not acknowledged yet, sent again on each connection. */private readonly unacked = new Map<string, { text: string; at: number }>();private readonly replies = new Map<string, JobReply | "running">();@@ -84,7 +145,12 @@ export class Agent {}get connected(): boolean {- return this.socket?.readyState === 1 && this.openedAt > 0;+ return this.connection?.phase === "open" && this.connection.socket.readyState === 1;+ }++ /** What the Admin said of this box last: pending until the team's Owner accepts it. */+ get state(): BoxState | null {+ return this.boxState;}start(): void {@@ -98,11 +164,10 @@ export class Agent {this.stopped = true;if (this.retry) this.clearTimer(this.retry);this.retry = null;- this.stopBeat();- const socket = this.socket;- this.socket = null;- this.openedAt = 0;- socket?.close(1000, "connector stopping");+ const connection = this.connection;+ this.detach();+ connection?.mux?.goAway();+ try { connection?.socket.close(1000, "connector stopping"); } catch { /* already closed */ }this.options.status?.({ connected: false });}@@ -123,7 +188,7 @@ export class Agent {private send(text: string): void {if (!this.connected) return;try {- this.socket!.send(text);+ this.connection!.socket.send(text);} catch (error) {this.options.log(`could not send to MausBot: ${errorText(error)}`);}@@ -131,46 +196,79 @@ export class Agent {private connect(): void {if (this.stopped) return;+ const identity = this.options.identity();let socket: Socket;try {- socket = (this.options.socket ?? nodeSocket)(connectUrl(this.options.admin), { authorization: `Bearer ${this.options.token}` });+ socket = (this.options.socket ?? nodeSocket)(connectUrl(identity.admin), { headers: { [BOX_HEADER]: identity.boxId }, protocols: [CHANNEL_PROTOCOL] });+ socket.binaryType = "arraybuffer";} catch (error) {this.options.log(`could not open the connection to MausBot: ${errorText(error)}`);this.scheduleRetry(backoffMs(this.attempt++, this.random()));return;}- this.socket = socket;+ const connection: Connection = { socket, phase: "challenge", adminNonce: "", boxNonce: "", count: 0, offset: 0, mux: null, heardAt: this.now(), pings: 0 };+ this.connection = connection;socket.onopen = () => {- if (this.socket !== socket) return;- this.openedAt = this.now();- this.options.status?.({ connected: true, unauthorized: false, lastConnectedAt: this.openedAt, lastError: null });- this.options.log("connected to MausBot");- for (const { text } of this.unacked.values()) socket.send(text);- this.startBeat();- this.onConnected?.();+ if (this.connection !== connection) return;+ this.deadline = this.setTimer(() => {+ if (this.connection === connection && connection.phase !== "open") this.drop(CLOSE_SILENT, "MausBot did not finish the handshake");+ }, this.options.handshakeMs ?? HANDSHAKE_MS);+ };+ socket.onmessage = (event) => {+ if (this.connection !== connection) return;+ connection.heardAt = this.now();+ this.received(connection, event.data);};- socket.onmessage = (event) => this.received(event.data);socket.onerror = () => {};socket.onclose = (event) => {- if (this.socket !== socket) return;- const wasOpen = this.openedAt > 0;- const lasted = wasOpen ? this.now() - this.openedAt : 0;- this.socket = null;- this.openedAt = 0;- this.stopBeat();- if (lasted >= STABLE_MS) this.attempt = 0;- if (event.code === CLOSE_UNAUTHORIZED) {- this.options.status?.({ connected: false, unauthorized: true, lastError: "MausBot no longer knows this server" });- this.options.log("MausBot no longer knows this server; run the install command again with a new code to connect it");- this.scheduleRetry(UNAUTHORIZED_RETRY_MS);- return;- }- this.options.status?.({ connected: false, lastError: wasOpen ? `the connection closed (${event.code})` : "MausBot could not be reached" });- if (wasOpen) this.options.log(`the connection to MausBot closed (${event.code}${event.reason ? `: ${event.reason}` : ""})`);- this.scheduleRetry(event.code === CLOSE_REPLACED ? REPLACED_RETRY_MS : backoffMs(this.attempt++, this.random()));+ if (this.connection !== connection) return;+ this.closed(event.code, event.reason);};}+ /** Forgets the connection at once: a dead network may never deliver its close. */+ private drop(code: number, why: string): void {+ const connection = this.connection;+ if (!connection) return;+ this.options.log(`dropping the connection to MausBot: ${why}`);+ try { connection.socket.close(code, why.slice(0, 120)); } catch { /* already closed */ }+ this.closed(code, why);+ }++ private detach(): void {+ const connection = this.connection;+ this.connection = null;+ this.openedAt = 0;+ for (const timer of [this.beat, this.tick, this.deadline]) if (timer) this.clearTimer(timer);+ this.beat = this.tick = this.deadline = null;+ connection?.mux?.close();+ }++ private closed(code: number, reason: string): void {+ const wasOpen = this.openedAt > 0;+ const lasted = wasOpen ? this.now() - this.openedAt : 0;+ this.detach();+ if (lasted >= STABLE_MS) this.attempt = 0;+ if (code === CLOSE_UNAUTHORIZED || code === CLOSE_KEY_COPIED) {+ const why = code === CLOSE_KEY_COPIED+ ? "MausBot saw another server use this server's key, so it stopped trusting the key"+ : "MausBot no longer knows this server";+ this.options.status?.({ connected: false, unauthorized: true, lastError: why });+ this.options.log(`${why}; run the install command again with a new code to connect it`);+ this.scheduleRetry(UNAUTHORIZED_RETRY_MS);+ return;+ }+ this.options.status?.({ connected: false, lastError: wasOpen ? `the connection closed (${code})` : "MausBot could not be reached" });+ if (wasOpen) this.options.log(`the connection to MausBot closed (${code}${reason ? `: ${reason}` : ""})`);+ if (this.restartIn !== null) {+ const wait = this.restartIn;+ this.restartIn = null;+ this.scheduleRetry(wait);+ return;+ }+ this.scheduleRetry(code === CLOSE_REPLACED ? REPLACED_RETRY_MS : backoffMs(this.attempt++, this.random()));+ }+private scheduleRetry(ms: number): void {if (this.stopped) return;if (this.retry) this.clearTimer(this.retry);@@ -180,46 +278,128 @@ export class Agent {}, ms);}- private startBeat(): void {- this.stopBeat();- const tick = () => {- this.heartbeat();- this.beat = this.setTimer(tick, this.options.heartbeatMs ?? HEARTBEAT_INTERVAL_MS);- };- tick();+ private received(connection: Connection, data: unknown): void {+ const bytes = bytesOf(data);+ if (bytes) {+ if (connection.phase !== "open" || !connection.mux) return this.drop(CLOSE_PROTOCOL, "a binary message before the handshake");+ connection.mux.receive(bytes);+ return;+ }+ const text = textOf(data);+ if (text === null || text.length > MAX_MESSAGE_BYTES) return this.drop(CLOSE_PROTOCOL, "a message too large");+ let message: Record<string, unknown>;+ try {+ const parsed: unknown = JSON.parse(text);+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");+ message = parsed as Record<string, unknown>;+ } catch {+ if (connection.phase !== "open") return this.drop(CLOSE_PROTOCOL, "a handshake message that is not JSON");+ this.options.log("ignored a message from MausBot that is not JSON");+ return;+ }+ if (connection.phase === "challenge") return this.challenged(connection, message);+ if (connection.phase === "hello") return this.greeted(connection, message);+ this.dispatch(connection, message);}- private stopBeat(): void {- if (this.beat) this.clearTimer(this.beat);- this.beat = null;+ private challenged(connection: Connection, message: Record<string, unknown>): void {+ if (message.t !== "challenge" || message.v !== 1 || !checkNonce(message.nonce)) return this.drop(CLOSE_PROTOCOL, "MausBot did not start the handshake");+ const identity = this.options.identity();+ let count: number;+ try {+ count = this.options.nextCount();+ } catch (error) {+ return this.drop(CLOSE_PROTOCOL, `the connection count could not be saved (${errorText(error)})`);+ }+ connection.adminNonce = message.nonce;+ connection.boxNonce = b64u(randomBytes(32));+ connection.count = count;+ connection.phase = "hello";+ const auth: Auth = { t: "auth", v: 1, box: identity.boxId, count, nonce: connection.boxNonce,+ sig: signText(identity.privateKey, authText(identity.boxId, connection.adminNonce, connection.boxNonce, count)) };+ connection.socket.send(JSON.stringify(auth));}- private heartbeat(): void {- this.options.heartbeat().then((beat) => {- if (!this.connected) return;- this.socket!.send(JSON.stringify(beat));- this.options.status?.({ lastHeartbeatAt: this.now() });- }, (error) => this.options.log(`could not make a heartbeat: ${errorText(error)}`));+ private greeted(connection: Connection, message: Record<string, unknown>): void {+ const identity = this.options.identity();+ const opened = message.t === "hello" ? unseal(message.signed, identity.adminKeys) : { ok: false as const, why: "not a hello" };+ if (!opened.ok) {+ this.options.status?.({ lastError: `the MausBot at ${identity.admin} did not prove it holds MausBot's key (${opened.why})` });+ return this.drop(CLOSE_PROTOCOL, `MausBot's hello did not verify: ${opened.why}`);+ }+ const hello = checkHello(opened.payload, { box: identity.boxId, adminNonce: connection.adminNonce, boxNonce: connection.boxNonce, count: connection.count });+ if (!hello.ok) return this.drop(CLOSE_PROTOCOL, hello.message);+ if (this.deadline) this.clearTimer(this.deadline);+ this.deadline = null;+ if (hello.value.keys) this.options.saveAdminKeys?.(hello.value.keys);+ connection.offset = hello.value.now - this.now();+ connection.phase = "open";+ connection.mux = new MuxSession("computer", {+ send: (frame) => connection.socket.send(frame),+ get bufferedAmount() { return connection.socket.bufferedAmount; },+ onceDrained: (listener) => this.whenDrained(connection, listener),+ }, {+ incoming: (stream, accept) => (this.options.stream ? this.options.stream(stream, accept) : stream.destroy()),+ failed: (reason) => this.drop(CLOSE_PROTOCOL, `a yamux error (${reason})`),+ });+ this.openedAt = this.now();+ this.setState(hello.value.state);+ this.options.status?.({ connected: true, unauthorized: false, lastConnectedAt: this.openedAt, lastError: null });+ this.options.log(`connected to MausBot (${hello.value.state === "pending" ? "waiting for the team's Owner to accept this server" : "accepted"})`);+ for (const { text } of this.unacked.values()) connection.socket.send(text);+ this.startBeat(connection);+ this.onConnected?.();+ }++ private whenDrained(connection: Connection, listener: () => void): void {+ const check = () => {+ if (this.connection !== connection || connection.socket.bufferedAmount <= 0) return listener();+ this.setTimer(check, DRAIN_POLL_MS);+ };+ this.setTimer(check, DRAIN_POLL_MS);}- private received(data: unknown): void {- const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : data instanceof ArrayBuffer ? Buffer.from(data).toString("utf8") : null;- if (text === null || text.length > MAX_MESSAGE_BYTES) {- this.options.log("ignored a message from MausBot that is not a job");+ private setState(state: BoxState): void {+ if (state === this.boxState) return;+ this.boxState = state;+ this.options.status?.({ boxState: state });+ }++ private dispatch(connection: Connection, message: Record<string, unknown>): void {+ if (isAck(message)) {+ this.unacked.delete(message.ack);return;}- let message: unknown;- try {- message = JSON.parse(text);- } catch {- this.options.log("ignored a message from MausBot that is not JSON");+ if (typeof message.job === "string") return this.signedJob(connection, message.job);+ if (typeof message.config === "string") return this.signedConfig(message.config);+ if (message.t === "restarting") {+ const wait = Math.min(RESTART_WAIT_MAX_MS, Math.max(0, Number(message.reconnectInMs) || 0));+ const spread = Math.min(RESTART_WAIT_MAX_MS, Math.max(0, Number(message.tryForMs) || 0));+ this.restartIn = Math.round(wait + this.random() * spread);return;}- if (isAck(message)) {- this.unacked.delete(message.ack);+ if ("id" in message || "type" in message) {+ this.refuse({ code: "unsigned_job", message: "a job MausBot did not sign" });return;}- const checked = checkJob(message);+ this.options.log("ignored a message from MausBot this connector does not know");+ }++ private refuse(refusal: Refusal, reply = false): void {+ this.options.log(`refused a job${refusal.id ? ` ${refusal.id}` : ""}: ${refusal.message}`);+ this.options.refused?.(refusal);+ if (reply && refusal.id) this.reply({ id: refusal.id, ok: false, error: { code: refusal.code, message: refusal.message } });+ }++ private signedJob(connection: Connection, envelope: string): void {+ const identity = this.options.identity();+ const opened = unseal(envelope, identity.adminKeys);+ if (!opened.ok) return this.refuse({ code: "unsigned_job", message: `a job MausBot did not sign (${opened.why})` });+ const payload = checkJobPayload(opened.payload, identity.boxId, this.now() + connection.offset);+ const claimed = typeof opened.payload.job === "object" && opened.payload.job !== null ? opened.payload.job as { id?: unknown; type?: unknown } : {};+ const id = typeof claimed.id === "string" ? claimed.id.slice(0, 64) : undefined;+ if (!payload.ok) return this.refuse({ code: payload.code, message: payload.message, id, type: typeof claimed.type === "string" ? claimed.type.slice(0, 32) : undefined }, true);+ const checked = checkJob(payload.job);if (!checked.ok) {if (checked.id) this.reply({ id: checked.id, ok: false, error: { code: checked.code, message: checked.message } });else this.options.log(`ignored a job without a valid id: ${checked.message}`);@@ -232,6 +412,9 @@ export class Agent {this.reply(known);return;}+ if (this.boxState !== "accepted" && !READS.has(job.type)) {+ return this.refuse({ code: "pending_box", message: "The team's Owner has not accepted this server in MausBot yet.", id: job.id, type: job.type }, true);+ }this.replies.set(job.id, "running");this.options.log(`job ${job.id}: ${job.type}`);this.options.handle(job).then((reply) => {@@ -243,4 +426,63 @@ export class Agent {this.reply(reply);}, (error) => this.reply({ id: job.id, ok: false, error: { code: "docker", message: errorText(error) } }));}++ private signedConfig(envelope: string): void {+ const identity = this.options.identity();+ const opened = unseal(envelope, identity.adminKeys);+ if (!opened.ok) return void this.options.log(`ignored a config MausBot did not sign (${opened.why})`);+ const config = checkConfig(opened.payload, identity.boxId);+ if (!config.ok) return void this.options.log(`ignored a config: ${config.message}`);+ this.setState(config.value.state);+ const saved = this.options.config?.saved();+ if (saved && saved.version >= config.value.version) return;+ try {+ this.options.config?.save({ envelope, version: config.value.version, savedAt: this.now() });+ } catch (error) {+ this.options.log(`could not keep MausBot's config on this server: ${errorText(error)}`);+ }+ this.options.onConfig?.(config.value);+ }++ private startBeat(connection: Connection): void {+ const beat = () => {+ this.heartbeat();+ this.beat = this.setTimer(beat, this.options.heartbeatMs ?? HEARTBEAT_INTERVAL_MS);+ };+ beat();+ const pingMs = this.options.pingMs ?? CHANNEL_PING_MS;+ const deadMs = this.options.deadMs ?? CHANNEL_DEAD_MS;+ const tick = () => {+ if (this.connection !== connection) return;+ // The wall clock: after a suspended VM resumes, it has moved on while timers stood still.+ if (this.now() - connection.heardAt > deadMs) return this.drop(CLOSE_SILENT, `nothing from MausBot for ${Math.round(deadMs / 1000)} s`);+ connection.pings = (connection.pings + 1) >>> 0;+ connection.mux?.ping(connection.pings);+ this.tick = this.setTimer(tick, pingMs);+ };+ this.tick = this.setTimer(tick, pingMs);+ }++ private heartbeat(): void {+ this.options.heartbeat().then((beat) => {+ if (!this.connected) return;+ this.connection!.socket.send(JSON.stringify(beat));+ this.options.status?.({ lastHeartbeatAt: this.now() });+ }, (error) => this.options.log(`could not make a heartbeat: ${errorText(error)}`));+ }+}++/** The saved config, verified again with the keys pinned now, for use while the Admin can't be reached. */+export function savedConfig(record: ConfigRecord | null, identity: AgentRecord): ConfigPayload | null {+ if (!record) return null;+ const opened = unseal(record.envelope, identity.adminKeys);+ if (!opened.ok) return null;+ const config = checkConfig(opened.payload, identity.boxId);+ return config.ok ? config.value : null;+}++/** `Authorization` for a transfer of job `jobId` to or from the Admin: a short token this box signs. */+export function transferAuthorization(identity: AgentRecord, jobId: string, now = Date.now()): string {+ const payload: Omit<TransferPayload, "kid"> = { t: "transfer", box: identity.boxId, job: jobId, iat: now, exp: now + TRANSFER_TOKEN_MS };+ return `${TRANSFER_SCHEME} ${seal(payload, "box", identity.privateKey)}`;}diff --git a/connector/src/audit.ts b/connector/src/audit.tsindex 0e10a75a27..892e75ef11 100644--- a/connector/src/audit.ts+++ b/connector/src/audit.ts@@ -6,13 +6,14 @@ import { createHash } from "node:crypto";import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync } from "node:fs";import { dirname } from "node:path";-import type { Job, JobError, JobType } from "./protocol.ts";+import type { Job, JobError, JobErrorCode, JobType } from "./protocol.ts";/** Who asked: the Admin over the connector's connection, or root on this server through `mausbot-connector job`. */export type AuditSource = "admin" | "local";export type AuditEvent =- | { event: "connector"; what: "started" | "enrolled"; version: string; image: string | null; serverId?: string }+ | { event: "connector"; what: "started" | "enrolled"; version: string; image: string | null; boxId?: string }+ | { event: "refused"; by: "admin"; code: JobErrorCode; why: string; id?: string; type?: string }| { event: "job"; by: AuditSource; id: string; type: JobType; args: Record<string, unknown> }| { event: "result"; by: AuditSource; id: string; type: JobType; ok: true; detail?: Record<string, unknown> }| { event: "result"; by: AuditSource; id: string; type: JobType; ok: false; error: JobError }diff --git a/connector/src/enroll.ts b/connector/src/enroll.tsindex 909fdf333e..64137036de 100644--- a/connector/src/enroll.ts+++ b/connector/src/enroll.ts@@ -1,8 +1,13 @@-// Trades the one-time code for this server's own agent token, once, over HTTPS.+// Trades the one-time code for this server's place in the team: a key made here, whose public half the Admin keeps, and+// the Admin's own keys, which the connector pins. Once, over HTTPS.import { errorText } from "./log.ts";-import { ENROLL_PATH, checkEnrollCode, checkEnrollResponse, isLoopbackHost, type ConnectorIdentity, type HostFacts } from "./protocol.ts";+import { ENROLL_PATH, checkEnrollCode, checkEnrollResponse, isLoopbackHost, type ConnectorIdentity, type EnrollRequest, type HostFacts } from "./protocol.ts";+import { generateKeyPair } from "./signed.ts";import type { AgentRecord } from "./state.ts";+/** A slow link or a busy Admin is not a refusal; the person runs the install command again if this passes. */+const ENROLL_TIMEOUT_MS = 2 * 60_000;+/** The Admin's origin: https, or http on this machine's loopback for a test Admin. */export function adminOrigin(raw: string | undefined): string {let url: URL;@@ -24,16 +29,19 @@ export async function enroll(options: {connector: ConnectorIdentity;fetch?: typeof fetch;now?: () => number;+ timeoutMs?: number;}): Promise<AgentRecord> {const code = checkEnrollCode(options.code.trim());if (!code.ok) throw new Error(code.message);+ const key = generateKeyPair();+ const request: EnrollRequest = { code: code.value, publicKey: key.publicKey, host: options.host, connector: options.connector };let response: Response;try {response = await (options.fetch ?? fetch)(`${options.admin}${ENROLL_PATH}`, {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ code: code.value, host: options.host, connector: options.connector }),- signal: AbortSignal.timeout(30_000),+ body: JSON.stringify(request),+ signal: AbortSignal.timeout(options.timeoutMs ?? ENROLL_TIMEOUT_MS),});} catch (error) {throw new Error(`This server can't reach MausBot at ${options.admin} (${errorText(error)}). Check that it can make outbound HTTPS connections, then run the install command again.`);@@ -46,5 +54,6 @@ export async function enroll(options: {try { body = await response.json(); } catch { body = null; }const checked = checkEnrollResponse(body);if (!checked.ok) throw new Error(`MausBot's answer could not be used (${checked.message}). Try the install command again.`);- return { version: 1, admin: options.admin, ...checked.value, enrolledAt: (options.now ?? Date.now)() };+ const { boxId, teamId, adminKeys } = checked.value;+ return { version: 2, admin: options.admin, boxId, teamId, publicKey: key.publicKey, privateKey: key.privateKey, adminKeys, enrolledAt: (options.now ?? Date.now)() };}diff --git a/connector/src/home-requests.ts b/connector/src/home-requests.tsnew file mode 100644index 0000000000..12e3de3cd9--- /dev/null+++ b/connector/src/home-requests.ts@@ -0,0 +1,157 @@+// The Admin's HTTP requests to the home, one per stream it opens: each is read up to its end, written to the audit log+// with the home's answer, and passed to the home's edge on this server's loopback, the only place a stream can reach.+// A second request on the same stream, a protocol upgrade or a chunked body is refused, so nothing passes unrecorded.+import { Transform, type Duplex, type TransformCallback } from "node:stream";++import { auditRequest, type AuditEvent } from "./audit.ts";++const MAX_HEAD_BYTES = 16 * 1024;+/** The body of a pairing request is read for the audit log (the member it opens a session for); it is small JSON. */+const MAX_RECORDED_BODY = 64 * 1024;+const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);+const PAIRING = "/api/cloud/pairing";++export interface RequestHead {+ method: string;+ target: string;+ length: number;+}++/** The request line and the headers that matter here, or why the request is refused. */+export function parseHead(head: string): { ok: true; head: RequestHead } | { ok: false; why: string } {+ const lines = head.split("\r\n");+ const match = /^([A-Z]{3,7}) (\/[^\s]*) HTTP\/1\.1$/.exec(lines[0] ?? "");+ if (!match || !METHODS.has(match[1]!)) return { ok: false, why: "not an HTTP/1.1 request MausBot may send" };+ let length = 0;+ for (const line of lines.slice(1)) {+ const colon = line.indexOf(":");+ if (colon <= 0) return { ok: false, why: "a malformed header" };+ const name = line.slice(0, colon).trim().toLowerCase();+ const value = line.slice(colon + 1).trim();+ if (name === "upgrade") return { ok: false, why: "a protocol upgrade" };+ if (name === "transfer-encoding") return { ok: false, why: "a chunked body" };+ if (name === "content-length") {+ if (!/^\d{1,15}$/.test(value)) return { ok: false, why: "a malformed content-length" };+ length = Number(value);+ }+ }+ return { ok: true, head: { method: match[1]!, target: match[2]!, length } };+}++/** Passes exactly one request through, then refuses anything more. */+export class RequestGate extends Transform {+ #head: Buffer = Buffer.alloc(0);+ #parsed: RequestHead | null = null;+ #remaining = 0;+ #body: Buffer[] | null = null;+ #bodyBytes = 0;+ readonly #onHead: (head: RequestHead) => void;+ readonly #onBody: (body: string | null) => void;++ constructor(onHead: (head: RequestHead) => void, onBody: (body: string | null) => void) {+ super();+ this.#onHead = onHead;+ this.#onBody = onBody;+ }++ override _transform(chunk: Buffer, _encoding: BufferEncoding, done: TransformCallback): void {+ let rest = chunk;+ if (!this.#parsed) {+ this.#head = Buffer.concat([this.#head, rest]);+ const end = this.#head.indexOf("\r\n\r\n");+ if (end < 0) return done(this.#head.length > MAX_HEAD_BYTES ? new Error("the request head is too large") : null);+ const parsed = parseHead(this.#head.subarray(0, end).toString("latin1"));+ if (!parsed.ok) return done(new Error(parsed.why));+ this.#parsed = parsed.head;+ this.#remaining = parsed.head.length;+ if (parsed.head.method === "POST" && parsed.head.target.split("?")[0] === PAIRING) this.#body = [];+ this.push(this.#head.subarray(0, end + 4));+ rest = this.#head.subarray(end + 4);+ this.#head = Buffer.alloc(0);+ this.#onHead(parsed.head);+ if (this.#remaining === 0) this.#ended();+ }+ if (rest.length > this.#remaining) return done(new Error("a second request on one stream"));+ if (rest.length > 0) {+ this.#remaining -= rest.length;+ if (this.#body && this.#bodyBytes + rest.length <= MAX_RECORDED_BODY) {+ this.#body.push(rest);+ this.#bodyBytes += rest.length;+ }+ this.push(rest);+ if (this.#remaining === 0) this.#ended();+ }+ done();+ }++ #ended(): void {+ this.#onBody(this.#body && this.#bodyBytes <= MAX_RECORDED_BODY ? Buffer.concat(this.#body).toString("utf8") : null);+ this.#body = null;+ }+}++/** Reads the status code off the first bytes of the home's answer and passes everything on. */+export class StatusTap extends Transform {+ #seen: Buffer | null = Buffer.alloc(0);+ readonly #onStatus: (status: number) => void;++ constructor(onStatus: (status: number) => void) {+ super();+ this.#onStatus = onStatus;+ }++ override _transform(chunk: Buffer, _encoding: BufferEncoding, done: TransformCallback): void {+ if (this.#seen) {+ this.#seen = Buffer.concat([this.#seen, chunk]);+ const line = /^HTTP\/1\.[01] (\d{3})/.exec(this.#seen.subarray(0, 32).toString("latin1"));+ if (line || this.#seen.length >= 32) {+ this.#onStatus(line ? Number(line[1]) : 0);+ this.#seen = null;+ }+ }+ done(null, chunk);+ }+}++const reply = (status: number, words: string) => `HTTP/1.1 ${status} ${words}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n`;++/** Serves one stream the Admin opened: the request it carries goes to the home, its answer comes back, both recorded. */+export function serveRequest(stream: Duplex, accept: () => void, options: { connectHome: () => Promise<Duplex>; record: (event: AuditEvent) => void }): void {+ let head: RequestHead | null = null;+ let body: string | null = null;+ let piped = false;+ let recorded = false;+ // A pairing's body has passed the gate before the home can answer it, so it is known when the status is.+ const record = (status: number) => {+ if (recorded || !head) return;+ recorded = true;+ options.record(auditRequest(head.method, head.target, status, body));+ };+ const gate = new RequestGate((parsed) => {+ head = parsed;+ options.connectHome().then((home) => {+ if (stream.destroyed) return void home.destroy();+ piped = true;+ home.on("error", () => stream.destroy());+ home.on("close", () => {+ record(0);+ if (!stream.writableEnded) stream.end();+ });+ stream.on("close", () => home.destroy());+ gate.pipe(home);+ home.pipe(new StatusTap(record)).pipe(stream);+ }, () => {+ record(502);+ stream.end(reply(502, "Bad Gateway"));+ });+ }, (read) => {+ body = read;+ });+ gate.on("error", () => {+ record(400);+ if (piped) stream.destroy();+ else if (!stream.destroyed) stream.end(reply(400, "Bad Request"));+ });+ accept();+ stream.pipe(gate);+}diff --git a/connector/src/home.ts b/connector/src/home.tsindex 1c61ebe1ef..365637c269 100644--- a/connector/src/home.ts+++ b/connector/src/home.ts@@ -317,7 +317,7 @@ export class Home {}/** A gzip tar of /data, copied while the home is stopped, then uploaded to the Admin once the home runs again. */- exportDisk(jobId: string, admin: { origin: string; token: string }): Promise<JobResults["export-disk"]> {+ exportDisk(jobId: string, admin: { origin: string; authorization: (jobId: string) => string }): Promise<JobResults["export-disk"]> {return this.exclusive(async () => {const { image } = this.current();await this.ensureRoomForCopy(image);@@ -338,7 +338,7 @@ export class Home {if (wasRunning) await this.restartAfter(image);this.phase({ phase: "upload" });try {- const sent = await this.options.transfer.upload(`${admin.origin}${EXPORT_PATH}/${jobId}`, { authorization: `Bearer ${admin.token}` }, this.state.path(archive));+ const sent = await this.options.transfer.upload(`${admin.origin}${EXPORT_PATH}/${jobId}`, { authorization: admin.authorization(jobId) }, this.state.path(archive));return { bytes: sent.bytes, sha256: sent.sha256 };} catch (error) {throw new JobFailure("transfer_failed", `The data could not be sent to MausBot (${errorText(error)}).`);@@ -350,7 +350,7 @@ export class Home {}/** Replaces /data with the gzip tar at `url`, keeping a safety copy until the home runs on it. */- importDisk(jobId: string, url: string, admin: { origin: string; token: string }): Promise<JobResults["import-disk"]> {+ importDisk(jobId: string, url: string, admin: { origin: string; authorization: (jobId: string) => string }): Promise<JobResults["import-disk"]> {return this.exclusive(async () => {const { image, env } = this.current();const archive = `import-${jobId}.tar.gz`;@@ -358,8 +358,8 @@ export class Home {this.begin({ jobId, type: "import-disk", phase: "download", previousImage: image, nextImage: null, target: archive, dataAtRisk: false, wasRunning });let bytes: number;try {- // The token goes only to the Admin itself, never to a storage address it hands out.- const headers: Record<string, string> = new URL(url).origin === admin.origin ? { authorization: `Bearer ${admin.token}` } : {};+ // The box's token goes only to the Admin itself, never to a storage address it hands out.+ const headers: Record<string, string> = new URL(url).origin === admin.origin ? { authorization: admin.authorization(jobId) } : {};bytes = (await this.options.transfer.download(url, headers, this.state.path(archive), Math.max(0, this.options.diskFree() - 2e9))).bytes;await this.ensureRoomForCopy(image);} catch (error) {diff --git a/connector/src/jobs.ts b/connector/src/jobs.tsindex 27c7b32f8c..28c461d3d5 100644--- a/connector/src/jobs.ts+++ b/connector/src/jobs.ts@@ -15,7 +15,8 @@ export interface RunnerDeps {home: Home;hostHealth: () => Promise<HostHealth>;identity: () => ConnectorIdentity;- admin: () => { origin: string; token: string };+ /** The Admin's origin, and the `Authorization` a transfer for a job sends it. */+ admin: () => { origin: string; authorization: (jobId: string) => string };/** Null when the new connector took over and will answer this job itself. */selfUpdate: (job: Job<"self-update">) => Promise<JobReply | null>;}diff --git a/connector/src/main.ts b/connector/src/main.tsindex 69e2d9293b..433a4da4d4 100644--- a/connector/src/main.ts+++ b/connector/src/main.ts@@ -3,11 +3,15 @@import { existsSync, readFileSync, statfsSync } from "node:fs";import { join } from "node:path";-import { Agent } from "./agent.ts";+import { createConnection } from "node:net";+import type { Duplex } from "node:stream";++import { Agent, savedConfig, transferAuthorization } from "./agent.ts";import { AuditLog, verifyAudit } from "./audit.ts";import { SocketDocker, type DockerInfo } from "./docker.ts";import { adminOrigin, enroll } from "./enroll.ts";import { readHealth } from "./home-health.ts";+import { serveRequest } from "./home-requests.ts";import { Home } from "./home.ts";import { hostChecks, hostFacts, hostHealth, probeBox, type BoxProbeResult, type HostReader } from "./host.ts";import { jobDesk, jobRunner, resultEvent } from "./jobs.ts";@@ -16,7 +20,7 @@ import { POLICY_FILE } from "./policy.ts";import { errorText, log, registerSecret } from "./log.ts";import { PROTOCOL_VERSION, type ConnectorIdentity, type Heartbeat, type HostHealth } from "./protocol.ts";import { SELF_UPDATE_DEADLINE_MS, SelfUpdater, ownContainer } from "./self-update.ts";-import { AUDIT_FILE, CONNECTOR_VERSION, PATHS, SECCOMP_FILE, envSeconds } from "./settings.ts";+import { AUDIT_FILE, CONNECTOR_VERSION, HOME_PORT, PATHS, SECCOMP_FILE, envSeconds } from "./settings.ts";import { StateStore, type AgentRecord } from "./state.ts";import { httpTransfer } from "./transfer.ts";@@ -112,9 +116,11 @@ async function run(): Promise<void> {await sleep(2_000);record = state.agent();}- registerSecret(record.agentToken);+ registerSecret(record.privateKey);let current: AgentRecord = record;- if (enrolledNow) note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, serverId: record.serverId });+ if (enrolledNow) note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, boxId: record.boxId });+ const kept = savedConfig(state.adminConfig(), current);+ if (kept) log(`going by MausBot's schedule and policy kept on this server (version ${kept.version}) until MausBot answers`);const host = hostReporter(docker, () => current.admin);const home = new Home({docker, state, log, readHealth, seccomp, transfer: httpTransfer,@@ -131,12 +137,29 @@ async function run(): Promise<void> {home,hostHealth: () => host.health(true),identity,- admin: () => ({ origin: current.admin, token: current.agentToken }),+ admin: () => ({ origin: current.admin, authorization: (jobId) => transferAuthorization(current, jobId) }),selfUpdate: (job) => home.exclusive(() => updater.run(job, { pause: () => agent.stop(), resume: () => agent.start() })),});const desk = jobDesk({ run: runner, audit, log, policyFile: join(PATHS.hostConfig, POLICY_FILE) });- const makeAgent = (from: AgentRecord) => new Agent({ admin: from.admin, token: from.agentToken, log, heartbeat, handle: (job) => desk.submit(job, "admin"), status: (patch) => state.saveStatus(patch) });- agent = makeAgent(current);+ const connectHome = () => new Promise<Duplex>((resolve, reject) => {+ const socket = createConnection({ host: "127.0.0.1", port: HOME_PORT });+ socket.once("connect", () => resolve(socket));+ socket.once("error", reject);+ });+ const makeAgent = () => new Agent({+ identity: () => current, log, heartbeat, handle: (job) => desk.submit(job, "admin"), status: (patch) => state.saveStatus(patch),+ nextCount: () => state.nextCount(),+ saveAdminKeys: (keys) => {+ current = { ...current, adminKeys: keys };+ state.saveAgent(current);+ log(`MausBot's signing keys are now ${Object.keys(keys).join(", ")}`);+ },+ config: { saved: () => state.adminConfig(), save: (config) => state.saveAdminConfig(config) },+ onConfig: (config) => log(`MausBot's schedule and policy (version ${config.version}) are kept on this server`),+ stream: (stream, accept) => serveRequest(stream, accept, { connectHome, record: note }),+ refused: (refusal) => note({ event: "refused", by: "admin", code: refusal.code, why: refusal.message, ...(refusal.id ? { id: refusal.id } : {}), ...(refusal.type ? { type: refusal.type } : {}) }),+ });+ agent = makeAgent();const role = await updater.atStart(() => new Promise<boolean>((resolve) => {const timer = setTimeout(() => resolve(false), SELF_UPDATE_DEADLINE_MS);@@ -173,13 +196,13 @@ async function run(): Promise<void> {setInterval(() => {home.supervise().catch((error) => log(`supervising the home failed: ${errorText(error)}`));const latest = state.agent();- if (latest && latest.agentToken !== current.agentToken) {+ if (latest && latest.publicKey !== current.publicKey) {log("this server was connected again with a new code; reconnecting");- registerSecret(latest.agentToken);+ registerSecret(latest.privateKey);current = latest;- note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, serverId: latest.serverId });+ note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, boxId: latest.boxId });agent.stop();- agent = makeAgent(current);+ agent = makeAgent();agent.start();}}, 10_000);@@ -206,7 +229,7 @@ async function enrollCommand(): Promise<void> {state.saveAgent(record);// Connected again only once the service has connected with this token.state.saveStatus({ connected: false, unauthorized: false, lastError: null });- console.log(`This server is connected to MausBot (server ${record.serverId}).`);+ console.log(`This server is connected to MausBot (server ${record.boxId}).`);}function statusCommand(): void {@@ -215,8 +238,9 @@ function statusCommand(): void {const status = state.status();const home = state.home();console.log(JSON.stringify({- enrolled: Boolean(record), admin: record?.admin ?? null, serverId: record?.serverId ?? null, cloudId: record?.cloudId ?? null,- connected: status.connected, unauthorized: status.unauthorized, lastConnectedAt: status.lastConnectedAt, lastHeartbeatAt: status.lastHeartbeatAt,+ enrolled: Boolean(record), admin: record?.admin ?? null, boxId: record?.boxId ?? null, teamId: record?.teamId ?? null,+ connected: status.connected, accepted: status.boxState === "accepted", unauthorized: status.unauthorized,+ lastConnectedAt: status.lastConnectedAt, lastHeartbeatAt: status.lastHeartbeatAt, config: state.adminConfig()?.version ?? null,lastError: status.lastError, home: { desired: home.desired, image: home.image, operation: home.operation?.type ?? null },}));}diff --git a/connector/src/mux.ts b/connector/src/mux.tsnew file mode 100644index 0000000000..61e84d0da4--- /dev/null+++ b/connector/src/mux.ts@@ -0,0 +1,231 @@+// yamux streams over the box channel's binary WebSocket messages, one frame per message, each stream a Node Duplex.+// The Admin opens every stream (yamux.ts calls that side the "phone"); the connector accepts each one (the "computer")+// and pipes it to the home. The Admin copies this file as it is.+import { Duplex } from "node:stream";++import { decodeFrame, encodeFrame, GO_AWAY, Mux, YamuxError, type Frame, type Role } from "./yamux.ts";++/** A sender stops writing frames while the socket holds more than this. */+export const SEND_BUFFER_HIGH = 1024 * 1024;++export interface FrameTransport {+ send(frame: Uint8Array): void;+ readonly bufferedAmount: number;+ onceDrained(listener: () => void): void;+}++export interface MuxHooks {+ /** The accepting side: a new stream. Call `accept()` once its far end is ready, or destroy the stream to refuse it. */+ incoming?(stream: MuxStream, accept: () => void): void;+ /** A frame broke the profile, or the peer went away with an error: the caller closes the connection. */+ failed(reason: string): void;+ pong?(value: number): void;+}++const noop = () => {};++export class MuxStream extends Duplex {+ readonly streamId: number;+ readonly #session: MuxSession;+ #pending: Buffer | null = null;+ #pendingDone: ((error?: Error | null) => void) | null = null;+ #ungranted = 0;++ constructor(session: MuxSession, streamId: number) {+ super({ allowHalfOpen: true, readableHighWaterMark: 256 * 1024 });+ this.#session = session;+ this.streamId = streamId;+ // A reset reaches whoever listens; without a listener it must not take the process down.+ this.on("error", noop);+ }++ override _write(chunk: Buffer, _encoding: BufferEncoding, done: (error?: Error | null) => void): void {+ this.#pending = chunk;+ this.#pendingDone = done;+ this.flush();+ }++ override _final(done: (error?: Error | null) => void): void {+ this.#session.mux.finish(this.streamId);+ done();+ }++ override _read(): void {+ if (this.#ungranted === 0) return;+ const bytes = this.#ungranted;+ this.#ungranted = 0;+ this.#session.mux.consumed(this.streamId, bytes);+ }++ override _destroy(error: Error | null, done: (error?: Error | null) => void): void {+ const mux = this.#session.mux;+ if (mux.has(this.streamId)) mux.reset(this.streamId);+ this.#session.forget(this.streamId);+ const pendingDone = this.#pendingDone;+ this.#pending = null;+ this.#pendingDone = null;+ pendingDone?.(error ?? new Error("stream reset"));+ done(error);+ }++ /** Node's HTTP client calls these on its socket; a stream has no TCP options to set. */+ setNoDelay(): this {+ return this;+ }++ setKeepAlive(): this {+ return this;+ }++ setTimeout(): this {+ return this;+ }++ ref(): this {+ return this;+ }++ unref(): this {+ return this;+ }++ /** Granted back as the reader takes it, so a slow reader slows the sender. */+ deliver(data: Buffer): void {+ if (this.push(data)) this.#session.mux.consumed(this.streamId, data.length);+ else this.#ungranted += data.length;+ }++ remoteEnded(): void {+ this.push(null);+ }++ remoteReset(): void {+ if (!this.destroyed) this.destroy(new Error("stream reset"));+ }++ flush(): void {+ const mux = this.#session.mux;+ while (this.#pending && this.#pending.length > 0) {+ if (!mux.has(this.streamId) || this.#session.closed) return void this.destroy(new Error("stream reset"));+ if (this.#session.congested) return this.#session.whenDrained(() => this.flush());+ const taken = mux.write(this.streamId, this.#pending);+ if (taken === 0) return;+ this.#pending = this.#pending.subarray(taken);+ }+ const done = this.#pendingDone;+ this.#pending = null;+ this.#pendingDone = null;+ done?.();+ }+}++export class MuxSession {+ readonly mux: Mux;+ readonly #transport: FrameTransport;+ readonly #hooks: MuxHooks;+ readonly #streams = new Map<number, MuxStream>();+ #drainWaiters: Array<() => void> = [];+ #closed = false;++ constructor(role: Role, transport: FrameTransport, hooks: MuxHooks) {+ this.#transport = transport;+ this.#hooks = hooks;+ this.mux = new Mux(role, {+ send: (frame) => this.#send(frame),+ opened: (streamId) => this.#incoming(streamId),+ data: (streamId, data) => this.#streams.get(streamId)?.deliver(Buffer.from(data.buffer, data.byteOffset, data.byteLength)),+ ended: (streamId) => this.#streams.get(streamId)?.remoteEnded(),+ reset: (streamId) => {+ const stream = this.#streams.get(streamId);+ this.#streams.delete(streamId);+ stream?.remoteReset();+ },+ writable: (streamId) => this.#streams.get(streamId)?.flush(),+ goAway: (code) => {+ if (code !== GO_AWAY.normal) this.#hooks.failed(`the peer went away (${code})`);+ },+ pong: (value) => this.#hooks.pong?.(value),+ });+ }++ get closed(): boolean {+ return this.#closed;+ }++ get congested(): boolean {+ return this.#transport.bufferedAmount > SEND_BUFFER_HIGH;+ }++ get activeStreams(): number {+ return this.#streams.size;+ }++ whenDrained(listener: () => void): void {+ this.#drainWaiters.push(listener);+ if (this.#drainWaiters.length > 1) return;+ this.#transport.onceDrained(() => {+ const waiters = this.#drainWaiters;+ this.#drainWaiters = [];+ for (const waiter of waiters) waiter();+ });+ }++ forget(streamId: number): void {+ this.#streams.delete(streamId);+ }++ /** One binary message from the peer: exactly one frame. */+ receive(message: Uint8Array): void {+ if (this.#closed) return;+ try {+ this.mux.receive(decodeFrame(message));+ } catch (error) {+ if (!(error instanceof YamuxError)) throw error;+ this.mux.protocolError();+ this.#hooks.failed(error.reason);+ }+ }++ /** The opening side. */+ openStream(): MuxStream {+ if (this.#closed) throw new YamuxError("closed");+ const streamId = this.mux.open();+ const stream = new MuxStream(this, streamId);+ this.#streams.set(streamId, stream);+ return stream;+ }++ ping(value: number): void {+ if (!this.#closed) this.mux.ping(value);+ }++ /** A planned close: GoAway first, so the peer knows it isn't an error. */+ goAway(): void {+ if (!this.#closed) this.mux.goAway(GO_AWAY.normal);+ }++ /** The connection is gone: every stream ends with a reset. */+ close(): void {+ if (this.#closed) return;+ this.#closed = true;+ this.mux.closeAll();+ for (const stream of this.#streams.values()) stream.remoteReset();+ this.#streams.clear();+ const waiters = this.#drainWaiters;+ this.#drainWaiters = [];+ for (const waiter of waiters) waiter();+ }++ #send(frame: Frame): void {+ if (!this.#closed) this.#transport.send(encodeFrame(frame));+ }++ #incoming(streamId: number): void {+ const stream = new MuxStream(this, streamId);+ this.#streams.set(streamId, stream);+ if (!this.#hooks.incoming) return void stream.destroy();+ this.#hooks.incoming(stream, () => {+ if (!stream.destroyed && !this.#closed) this.mux.accept(streamId);+ });+ }+}diff --git a/connector/src/protocol.ts b/connector/src/protocol.tsindex 1b20e84155..3f7dc4df82 100644--- a/connector/src/protocol.ts+++ b/connector/src/protocol.ts@@ -1,23 +1,49 @@-// MausBot connector protocol v1: what the connector on an own server and the MausBot Cloud Admin say to each other.-// The Admin side copies this file as it is: it imports nothing.+// MausBot connector protocol v2: what the connector on an own server (a "box") and the MausBot Cloud Admin say to each+// other. The Admin side copies this file as it is: it imports nothing.//-// The connector only ever calls out. It enrols once over HTTPS with a one-time code, then holds one WebSocket to the-// Admin and runs the jobs the Admin sends on it; jobs that change the home or the connector run one at a time. There is-// no shell and no other command. Disk transfers are HTTPS, authorized with the same agent token.--export const PROTOCOL_VERSION = 1;+// The connector only ever calls out. It enrols once over HTTPS with a one-time code, sending the public half of an+// Ed25519 key it made and keeps; the Admin answers with its own signing keys, which the connector pins. Then it holds+// one WebSocket to the Admin. Each connection starts with both sides proving their keys (`authText`, `HelloPayload`),+// and the connector's count of its connections, which only goes up: a count the Admin has seen before means a copy of+// the key, and the Admin revokes it. Text messages carry JSON: jobs signed by the Admin for this box only, their+// replies, heartbeats and the Admin's signed schedule and policy. Binary messages carry yamux frames (yamux.ts, the+// phone relay's profile): the Admin opens a stream per HTTP request to the home, and the connector pipes it to the+// home's edge on this server and nowhere else. There is no shell and no other command. Disk transfers are HTTPS,+// authorized with a short token the connector signs (`TransferPayload`).++export const PROTOCOL_VERSION = 2;/** `POST {admin}{ENROLL_PATH}` with an `EnrollRequest`; answers an `EnrollResponse`. The code is single use. */-export const ENROLL_PATH = "/api/cloud/servers/agent/enroll";-/** `GET {admin}{CONNECT_PATH}`, upgraded to a WebSocket, with `Authorization: Bearer <agentToken>`. */-export const CONNECT_PATH = "/api/cloud/servers/agent/connect";+export const ENROLL_PATH = "/api/cloud/box/v1/enroll";+/** `GET {admin}{CONNECT_PATH}`, upgraded to a WebSocket with subprotocol `CHANNEL_PROTOCOL` and header `x-omb-box`. */+export const CONNECT_PATH = "/api/cloud/box/v1/connect";+export const CHANNEL_PROTOCOL = "omb-box.v2";+export const BOX_HEADER = "x-omb-box";/** `PUT {admin}{EXPORT_PATH}/<job id>`, `content-type: application/gzip`: an `export-disk` job's archive of `/data`. */-export const EXPORT_PATH = "/api/cloud/servers/agent/export";+export const EXPORT_PATH = "/api/cloud/box/v1/export";+/** `Authorization: Box <envelope>` on a transfer to or from the Admin: a `TransferPayload` the box signed. */+export const TRANSFER_SCHEME = "Box";-/** The Admin closes the WebSocket with this code when it no longer knows the token: the server was removed. */+/** The Admin closes the WebSocket with this code when it does not know the box's key, or the key was revoked. */export const CLOSE_UNAUTHORIZED = 4401;-/** The Admin closes an older WebSocket with this code when a newer one with the same token connects. */+/** The Admin saw a second server with this box's key (a connection count it had seen before) and revoked the key. */+export const CLOSE_KEY_COPIED = 4403;+/** The Admin closes an older WebSocket with this code when a newer one of the same box connects. */export const CLOSE_REPLACED = 4409;+/** Either side: a message out of order or malformed, a yamux error, or a key that does not verify. */+export const CLOSE_PROTOCOL = 4000;+/** Either side: nothing arrived for `CHANNEL_DEAD_MS`. */+export const CLOSE_SILENT = 4002;++/** Each side sends a yamux ping this often; a connection with nothing received for `CHANNEL_DEAD_MS` is dropped. */+export const CHANNEL_PING_MS = 20_000;+export const CHANNEL_DEAD_MS = 90_000;+/** How long either side waits for the other's half of the handshake. */+export const HANDSHAKE_MS = 60_000;+/** A signed job is refused this long after the Admin signed it (by the Admin's clock, which the hello carries). */+export const JOB_LIFETIME_MS = 15 * 60_000;+/** A transfer token lasts this long; an upload or download only has to start within it. */+export const TRANSFER_TOKEN_MS = 10 * 60_000;/** How often the connector sends a heartbeat while connected. */export const HEARTBEAT_INTERVAL_MS = 30_000;@@ -122,7 +148,7 @@ export interface JobArgs {restore: { backupId: string };/** Uploads a gzip tar of `/data` to `PUT {admin}{EXPORT_PATH}/<job id>`. */"export-disk": Record<string, never>;- /** Replaces `/data` with the gzip tar at `url` (https; the agent token is sent only to the Admin's own origin). */+ /** Replaces `/data` with the gzip tar at `url` (https; a transfer token goes only to the Admin's own origin). */"import-disk": { url: string };"host-health": Record<string, never>;/** Swaps the connector itself for `image`, keeping the current one until the new one has connected. */@@ -156,7 +182,8 @@ export interface JobResults {export type JobErrorCode =| "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted" | "audit_unavailable" | "refused_by_policy"| "no_home" | "docker" | "pull_failed" | "unhealthy" | "update_rolled_back" | "rollback_failed"- | "not_found" | "disk_full" | "port_in_use" | "box_unavailable" | "transfer_failed" | "self_update_failed";+ | "not_found" | "disk_full" | "port_in_use" | "box_unavailable" | "transfer_failed" | "self_update_failed"+ | "unsigned_job" | "wrong_box" | "expired_job" | "pending_box";/** `message` is plain words for the Admin's log and alerts; it never carries a secret. */export interface JobError {@@ -177,17 +204,122 @@ export interface JobAck {ack: string;}-/** `POST {admin}{ENROLL_PATH}` body. */+/** `POST {admin}{ENROLL_PATH}` body. `publicKey`: the box key's raw 32 bytes, base64url. */export interface EnrollRequest {code: string;+ publicKey: string;host: HostFacts;connector: ConnectorIdentity;}+/**+ * A box the team's Owner has not accepted yet is `pending`: it connects and reports its health, and the Admin sends it no+ * job that carries the team's data or changes anything. `revoked` is never sent: a revoked key is refused (4401).+ */+export type BoxState = "pending" | "accepted";+export interface EnrollResponse {- serverId: string;- cloudId: string;- agentToken: string;+ boxId: string;+ teamId: string;+ /** The Admin's signing keys by id, raw Ed25519 public keys in base64url; the connector pins them. One or two (rotation). */+ adminKeys: Record<string, string>;+ state: BoxState;+}++/** Admin → connector, the first message on every connection. `nonce`: 32 random bytes, base64url. */+export interface Challenge {+ t: "challenge";+ v: 1;+ nonce: string;+}++/** Connector → Admin: `sig` is the box key's signature of `authText(box, challenge nonce, nonce, count)`. */+export interface Auth {+ t: "auth";+ v: 1;+ box: string;+ count: number;+ nonce: string;+ sig: string;+}++export function authText(box: string, adminNonce: string, boxNonce: string, count: number): string {+ return `omb-box auth v1\n${box}\n${adminNonce}\n${boxNonce}\n${count}`;+}++/** Admin → connector, `{t: "hello", signed}`: an envelope (signed.ts) of this payload, under a key the connector pinned. */+export interface HelloPayload {+ t: "hello";+ kid: string;+ box: string;+ adminNonce: string;+ boxNonce: string;+ count: number;+ /** The Admin's clock (ms); the connector judges a job's age by it, whatever its own clock says. */+ now: number;+ state: BoxState;+ /** The Admin's signing keys from now on (rotation); absent: unchanged. */+ keys?: Record<string, string>;+}++/** Admin → connector, `{job: envelope}`. Only for this box, only while `exp` (the Admin's clock) has not passed. */+export interface JobPayload {+ t: "job";+ kid: string;+ box: string;+ iat: number;+ exp: number;+ job: Job;+}++/** The update window, in the server's time zone (`days`: 0 is Sunday; `end` before `start` runs past midnight). */+export interface UpdateWindow {+ days: number[];+ start: string;+ end: string;+ timeZone: string;+}++/**+ * Admin → connector, `{config: envelope}`, after each hello and on each change; a higher `version` replaces a lower one.+ * The connector keeps the newest it verified on its disk and goes by it while the Admin can't be reached.+ */+export interface ConfigPayload {+ t: "config";+ kid: string;+ box: string;+ iat: number;+ version: number;+ state: BoxState;+ schedule: {+ window: UpdateWindow | null;+ ring: "early" | "standard" | "late";+ /** Updates wait until then (ms). */+ holdUntil: number | null;+ /** The home image this server should run. */+ image: string | null;+ };+ policy: {+ /** How long members' sessions last past the Admin's last check while it can't be reached. */+ offlineHours: number;+ };+}++/** Admin → connector before it restarts: reconnect after `reconnectInMs` plus a random part of `tryForMs`. */+export interface Restarting {+ t: "restarting";+ reconnectInMs: number;+ tryForMs: number;+}++/** What the box signs for `Authorization: Box <envelope>` on a transfer; `kid` is "box". */+export interface TransferPayload {+ t: "transfer";+ kid: "box";+ box: string;+ job: string;+ iat: number;+ exp: number;}// Validation, shared so both sides refuse the same things.@@ -195,7 +327,6 @@ export interface EnrollResponse {const JOB_ID = /^[A-Za-z0-9_-]{1,64}$/;const BACKUP_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;const OPAQUE_ID = /^[A-Za-z0-9_-]{1,128}$/;-const TOKEN = /^[A-Za-z0-9_.~-]{32,512}$/;const ENV_NAME = /^OMB_[A-Z0-9_]{1,60}$/;// oxlint-disable-next-line no-control-regexconst ENV_VALUE = /^[^\0\r\n]{0,8192}$/;@@ -318,13 +449,77 @@ function checkArgs(type: JobType, args: Record<string, unknown>): Checked<JobArg}}+const B64U_KEY = /^[A-Za-z0-9_-]{43}$/;+const KEY_ID = /^[a-z0-9]{1,16}$/;+const NONCE = /^[A-Za-z0-9_-]{43}$/;+const BOX_ID = /^[A-Za-z0-9_-]{8,64}$/;+const isBoxState = (value: unknown): value is BoxState => value === "pending" || value === "accepted";+const isTime = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value > 0;++export const checkBoxId = (value: unknown): value is string => typeof value === "string" && BOX_ID.test(value);+export const checkNonce = (value: unknown): value is string => typeof value === "string" && NONCE.test(value);++/** One or two signing keys by id, each a raw Ed25519 public key in base64url. */+export function checkKeys(value: unknown): Checked<Record<string, string>> {+ if (!plainObject(value)) return { ok: false, message: "keys must be an object" };+ const entries = Object.entries(value);+ if (entries.length < 1 || entries.length > 2) return { ok: false, message: "one or two keys" };+ for (const [kid, key] of entries) if (!KEY_ID.test(kid) || typeof key !== "string" || !B64U_KEY.test(key)) return { ok: false, message: "a key is malformed" };+ return { ok: true, value: Object.fromEntries(entries) as Record<string, string> };+}+export function checkEnrollResponse(value: unknown): Checked<EnrollResponse> {if (!plainObject(value)) return { ok: false, message: "the enrolment answer is not a JSON object" };- const { serverId, cloudId, agentToken } = value;- if (typeof serverId !== "string" || !OPAQUE_ID.test(serverId)) return { ok: false, message: "the enrolment answer has no valid serverId" };- if (typeof cloudId !== "string" || !OPAQUE_ID.test(cloudId)) return { ok: false, message: "the enrolment answer has no valid cloudId" };- if (typeof agentToken !== "string" || !TOKEN.test(agentToken)) return { ok: false, message: "the enrolment answer has no valid agentToken" };- return { ok: true, value: { serverId, cloudId, agentToken } };+ const { boxId, teamId, adminKeys, state } = value;+ if (!checkBoxId(boxId)) return { ok: false, message: "the enrolment answer has no valid boxId" };+ if (typeof teamId !== "string" || !OPAQUE_ID.test(teamId)) return { ok: false, message: "the enrolment answer has no valid teamId" };+ const keys = checkKeys(adminKeys);+ if (!keys.ok) return { ok: false, message: `the enrolment answer's adminKeys: ${keys.message}` };+ if (!isBoxState(state)) return { ok: false, message: "the enrolment answer has no valid state" };+ return { ok: true, value: { boxId, teamId, adminKeys: keys.value, state } };+}++/** A verified hello's payload for this connection: this box, both nonces, this count. */+export function checkHello(payload: Record<string, unknown>, expected: { box: string; adminNonce: string; boxNonce: string; count: number }): Checked<HelloPayload> {+ if (payload.t !== "hello") return { ok: false, message: "not a hello" };+ if (payload.box !== expected.box) return { ok: false, message: "the hello is for another box" };+ if (payload.adminNonce !== expected.adminNonce || payload.boxNonce !== expected.boxNonce || payload.count !== expected.count) return { ok: false, message: "the hello is not for this connection" };+ if (!isTime(payload.now) || !isBoxState(payload.state)) return { ok: false, message: "the hello is malformed" };+ if (payload.keys !== undefined && !checkKeys(payload.keys).ok) return { ok: false, message: "the hello's keys are malformed" };+ return { ok: true, value: payload as unknown as HelloPayload };+}++/** A verified job envelope's payload: for `box`, signed at most `JOB_LIFETIME_MS` ago by the Admin's clock (`adminNow`). */+export function checkJobPayload(payload: Record<string, unknown>, box: string, adminNow: number): { ok: true; job: unknown } | { ok: false; code: "wrong_box" | "expired_job" | "unsigned_job"; message: string } {+ if (payload.t !== "job" || !isTime(payload.iat) || !isTime(payload.exp)) return { ok: false, code: "unsigned_job", message: "not a signed job" };+ if (payload.box !== box) return { ok: false, code: "wrong_box", message: "the job was signed for another server" };+ if (payload.exp - payload.iat > JOB_LIFETIME_MS || adminNow > payload.exp || adminNow < payload.iat - JOB_LIFETIME_MS) {+ return { ok: false, code: "expired_job", message: "the job's signature is too old" };+ }+ return { ok: true, job: payload.job };+}++const CLOCK = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;+const TIME_ZONE = /^[A-Za-z][A-Za-z0-9_+/-]{0,63}$/;++/** A verified config envelope's payload for `box`. */+export function checkConfig(payload: Record<string, unknown>, box: string): Checked<ConfigPayload> {+ if (payload.t !== "config" || payload.box !== box) return { ok: false, message: "the config is for another box" };+ if (!isTime(payload.iat) || typeof payload.version !== "number" || !Number.isSafeInteger(payload.version) || payload.version < 1 || !isBoxState(payload.state)) {+ return { ok: false, message: "the config is malformed" };+ }+ const schedule = payload.schedule, policy = payload.policy;+ if (!plainObject(schedule) || !plainObject(policy)) return { ok: false, message: "the config is malformed" };+ const window = schedule.window;+ if (window !== null && (!plainObject(window) || !Array.isArray(window.days) || window.days.length > 7+ || window.days.some((day) => !Number.isInteger(day) || (day as number) < 0 || (day as number) > 6)+ || typeof window.start !== "string" || !CLOCK.test(window.start) || typeof window.end !== "string" || !CLOCK.test(window.end)+ || typeof window.timeZone !== "string" || !TIME_ZONE.test(window.timeZone))) return { ok: false, message: "the update window is malformed" };+ if (!["early", "standard", "late"].includes(schedule.ring as string)) return { ok: false, message: "the ring is malformed" };+ if (schedule.holdUntil !== null && !isTime(schedule.holdUntil)) return { ok: false, message: "the hold is malformed" };+ if (schedule.image !== null && (typeof schedule.image !== "string" || !HOME_IMAGE.test(schedule.image))) return { ok: false, message: "the image is malformed" };+ if (typeof policy.offlineHours !== "number" || !Number.isInteger(policy.offlineHours) || policy.offlineHours < 0 || policy.offlineHours > 720) return { ok: false, message: "the policy is malformed" };+ return { ok: true, value: payload as unknown as ConfigPayload };}/** A one-time code as the Admin shows it: letters, digits and dashes. */diff --git a/connector/src/signed.ts b/connector/src/signed.tsnew file mode 100644index 0000000000..0b95b27f6c--- /dev/null+++ b/connector/src/signed.ts@@ -0,0 +1,85 @@+// Ed25519 keys and signed envelopes for the box channel. An envelope is the relay token's shape:+// b64u(payload JSON) "." b64u(Ed25519 signature over the ASCII bytes of the first part), and the payload names the key+// (`kid`) that signed it. The Admin copies this file as it is: it imports only node:crypto.+import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify, type KeyObject } from "node:crypto";++/** The DER prefix that makes a raw 32-byte Ed25519 public key an SPKI document (RFC 8410). */+const SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");+const B64U = /^[A-Za-z0-9_-]*$/;+export const MAX_ENVELOPE_BYTES = 256 * 1024;++export const b64u = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");++export function fromB64u(text: string): Buffer | null {+ return typeof text === "string" && B64U.test(text) ? Buffer.from(text, "base64url") : null;+}++/** A public key as the wire carries it: the raw 32 bytes, base64url (43 characters). */+export function isPublicKey(value: unknown): value is string {+ return typeof value === "string" && value.length === 43 && fromB64u(value)?.length === 32;+}++export interface KeyPair {+ /** Raw 32 bytes, base64url. */+ publicKey: string;+ /** PKCS #8 DER, base64url. A secret. */+ privateKey: string;+}++export function generateKeyPair(): KeyPair {+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");+ const spki = publicKey.export({ format: "der", type: "spki" });+ return { publicKey: b64u(spki.subarray(SPKI_PREFIX.length)), privateKey: b64u(privateKey.export({ format: "der", type: "pkcs8" })) };+}++export function publicKeyOf(privateKey: string): string {+ const spki = createPublicKey(privateKeyObject(privateKey)).export({ format: "der", type: "spki" });+ return b64u(spki.subarray(SPKI_PREFIX.length));+}++function privateKeyObject(privateKey: string): KeyObject {+ return createPrivateKey({ key: fromB64u(privateKey) ?? Buffer.alloc(0), format: "der", type: "pkcs8" });+}++function publicKeyObject(publicKey: string): KeyObject | null {+ if (!isPublicKey(publicKey)) return null;+ return createPublicKey({ key: Buffer.concat([SPKI_PREFIX, fromB64u(publicKey)!]), format: "der", type: "spki" });+}++export function signText(privateKey: string, text: string): string {+ return b64u(sign(null, Buffer.from(text, "utf8"), privateKeyObject(privateKey)));+}++export function verifyText(publicKey: string, text: string, signature: string): boolean {+ const key = publicKeyObject(publicKey);+ const bytes = fromB64u(signature);+ if (!key || !bytes || bytes.length !== 64) return false;+ try {+ return verify(null, Buffer.from(text, "utf8"), key, bytes);+ } catch {+ return false;+ }+}++/** Signs `payload`, which gains `kid`. */+export function seal(payload: Record<string, unknown>, kid: string, privateKey: string): string {+ const body = b64u(Buffer.from(JSON.stringify({ ...payload, kid }), "utf8"));+ return `${body}.${signText(privateKey, body)}`;+}++/** The payload of an envelope signed by one of `keys` (by its `kid`), or why not. Nothing in an unverified envelope is trusted. */+export function unseal(envelope: unknown, keys: Readonly<Record<string, string>>): { ok: true; payload: Record<string, unknown> } | { ok: false; why: string } {+ if (typeof envelope !== "string" || envelope.length > MAX_ENVELOPE_BYTES) return { ok: false, why: "not an envelope" };+ const dot = envelope.indexOf(".");+ if (dot <= 0 || envelope.indexOf(".", dot + 1) !== -1) return { ok: false, why: "not an envelope" };+ const body = envelope.slice(0, dot);+ const json = fromB64u(body);+ if (!json) return { ok: false, why: "not an envelope" };+ let payload: unknown;+ try { payload = JSON.parse(json.toString("utf8")); } catch { return { ok: false, why: "not an envelope" }; }+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return { ok: false, why: "not an envelope" };+ const kid = (payload as { kid?: unknown }).kid;+ if (typeof kid !== "string" || !Object.hasOwn(keys, kid)) return { ok: false, why: "signed by a key this side does not know" };+ if (!verifyText(keys[kid]!, body, envelope.slice(dot + 1))) return { ok: false, why: "the signature does not verify" };+ return { ok: true, payload: payload as Record<string, unknown> };+}diff --git a/connector/src/state.ts b/connector/src/state.tsindex e0cf77af80..1c62b6efd7 100644--- a/connector/src/state.ts+++ b/connector/src/state.ts@@ -1,17 +1,28 @@// The connector's state volume: small JSON files, each written whole (temp file, then rename) and readable by root only,-// in a folder only root may enter. The agent token and the home's environment live here and nowhere else.+// in a folder only root may enter. The box's private key and the home's environment live here and nowhere else.import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";export interface AgentRecord {- version: 1;+ version: 2;admin: string;- serverId: string;- cloudId: string;- agentToken: string;+ boxId: string;+ teamId: string;+ /** The box key: its public half as the Admin has it, and its private half (PKCS #8, base64url), a secret. */+ publicKey: string;+ privateKey: string;+ /** The Admin's signing keys by id, pinned at enrolment; only a hello signed by one of them replaces them. */+ adminKeys: Record<string, string>;enrolledAt: number;}+/** The Admin's newest signed config this box verified (protocol.ts `ConfigPayload`), kept as signed. */+export interface ConfigRecord {+ envelope: string;+ version: number;+ savedAt: number;+}+/** A step of a job that changes the home or its data, written before the step starts, so a restart can finish it. */export interface Operation {jobId: string;@@ -41,6 +52,8 @@ export interface HomeRecord {export interface StatusRecord {connected: boolean;unauthorized: boolean;+ /** What the Admin last said of this box: the team's Owner has not accepted it yet, or has. */+ boxState?: "pending" | "accepted" | null;lastConnectedAt: number | null;lastHeartbeatAt: number | null;lastError: string | null;@@ -64,6 +77,8 @@ const FILES = {env: "home-env.json",status: "status.json",selfUpdate: "self-update.json",+ count: "connect-count.json",+ config: "admin-config.json",} as const;export class StateStore {@@ -101,8 +116,29 @@ export class StateStore {rmSync(this.path(name), { force: true });}+ /** Null until enrolled; a record from protocol v1 (a bearer token, no key) counts as not enrolled. */agent(): AgentRecord | null {- return this.read<AgentRecord>(FILES.agent);+ const record = this.read<AgentRecord | { version: 1 }>(FILES.agent);+ return record?.version === 2 ? record : null;+ }++ /**+ * The next connection's count, written before it is sent, so no count is ever sent twice: the Admin takes a count it+ * has seen before for a copy of this box's key. It is read from the disk each time, as a connector taking over in a+ * self-update shares it.+ */+ nextCount(): number {+ const count = (this.read<{ count: number }>(FILES.count)?.count ?? 0) + 1;+ this.write(FILES.count, { count });+ return count;+ }++ adminConfig(): ConfigRecord | null {+ return this.read<ConfigRecord>(FILES.config);+ }++ saveAdminConfig(record: ConfigRecord): void {+ this.write(FILES.config, record);}saveAgent(record: AgentRecord): void {diff --git a/connector/src/yamux.ts b/connector/src/yamux.tsnew file mode 100644index 0000000000..a167662de1--- /dev/null+++ b/connector/src/yamux.ts@@ -0,0 +1,335 @@+// The yamux profile carried inside the records: one frame per record, phone-opened streams only, 2 MiB windows.+// Wire spec: companion/src/e2e/README.md, "Multiplexing". This module does no I/O, so every rule is testable.++export const VERSION = 0;+export const TYPE = { data: 0, windowUpdate: 1, ping: 2, goAway: 3 } as const;+export const FLAG = { syn: 0x1, ack: 0x2, fin: 0x4, rst: 0x8 } as const;+const KNOWN_FLAGS = 0xf;+/** `removed` goes only from the computer to the phone: this device was removed, and the close that follows is 4001. It+ * is inside the encryption, so unlike a bare 4001 close code a relay can't forge it. */+export const GO_AWAY = { normal: 0, protocol: 1, internal: 2, removed: 3 } as const;++export const HEADER_BYTES = 12;+export const MAX_DATA_PAYLOAD = 65_507;+export const INITIAL_WINDOW = 256 * 1024;+export const STREAM_WINDOW = 2 * 1024 * 1024;+export const OPEN_WINDOW_DELTA = STREAM_WINDOW - INITIAL_WINDOW;+export const WINDOW_UPDATE_AFTER = 1024 * 1024;+export const MAX_STREAMS = 64;+export const MAX_STREAM_ID = 2 ** 31 - 1;+export const PING_INTERVAL_MS = 20_000;+export const PING_TIMEOUT_MS = 10_000;++export type FrameType = (typeof TYPE)[keyof typeof TYPE];++export interface Frame {+ type: FrameType;+ flags: number;+ streamId: number;+ /** Data: the payload size. WindowUpdate: the window delta. Ping: the opaque value. GoAway: the code. */+ length: number;+ data?: Uint8Array;+}++export class YamuxError extends Error {+ readonly reason: string;+ constructor(reason: string) {+ super(`yamux: ${reason}`);+ this.reason = reason;+ }+}++export function encodeFrame(frame: Frame): Buffer {+ const payload = frame.type === TYPE.data ? frame.data ?? new Uint8Array(0) : new Uint8Array(0);+ if (frame.type === TYPE.data && payload.length !== frame.length) throw new YamuxError("data_length");+ if (payload.length > MAX_DATA_PAYLOAD) throw new YamuxError("data_too_large");+ const out = Buffer.alloc(HEADER_BYTES + payload.length);+ out.writeUInt8(VERSION, 0);+ out.writeUInt8(frame.type, 1);+ out.writeUInt16BE(frame.flags, 2);+ out.writeUInt32BE(frame.streamId, 4);+ out.writeUInt32BE(frame.length, 8);+ out.set(payload, HEADER_BYTES);+ return out;+}++/** One record's plaintext is exactly one frame. Everything that can be checked without stream state is+ * checked here. */+export function decodeFrame(bytes: Uint8Array): Frame {+ if (bytes.length < HEADER_BYTES) throw new YamuxError("short_frame");+ const view = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (view.readUInt8(0) !== VERSION) throw new YamuxError("version");+ const type = view.readUInt8(1);+ if (type > TYPE.goAway) throw new YamuxError("type");+ const flags = view.readUInt16BE(2);+ if ((flags & ~KNOWN_FLAGS) !== 0) throw new YamuxError("flags");+ const streamId = view.readUInt32BE(4);+ const length = view.readUInt32BE(8);+ if (type === TYPE.data) {+ if (length > MAX_DATA_PAYLOAD) throw new YamuxError("data_too_large");+ if (bytes.length !== HEADER_BYTES + length) throw new YamuxError("data_length");+ if (streamId === 0) throw new YamuxError("stream_zero");+ return { type, flags, streamId, length, data: view.subarray(HEADER_BYTES) };+ }+ if (bytes.length !== HEADER_BYTES) throw new YamuxError("trailing_bytes");+ if (type === TYPE.windowUpdate) {+ if (streamId === 0) throw new YamuxError("stream_zero");+ } else {+ if (streamId !== 0) throw new YamuxError("session_frame_stream");+ if (type === TYPE.ping && flags !== FLAG.syn && flags !== FLAG.ack) throw new YamuxError("ping_flags");+ if (type === TYPE.goAway && flags !== 0) throw new YamuxError("goaway_flags");+ }+ return { type: type as FrameType, flags, streamId, length };+}++export const openFrame = (streamId: number): Frame => ({ type: TYPE.windowUpdate, flags: FLAG.syn, streamId, length: OPEN_WINDOW_DELTA });+export const acceptFrame = (streamId: number): Frame => ({ type: TYPE.windowUpdate, flags: FLAG.ack, streamId, length: OPEN_WINDOW_DELTA });+export const resetFrame = (streamId: number): Frame => ({ type: TYPE.windowUpdate, flags: FLAG.rst, streamId, length: 0 });+export const finFrame = (streamId: number): Frame => ({ type: TYPE.windowUpdate, flags: FLAG.fin, streamId, length: 0 });+export const windowFrame = (streamId: number, delta: number): Frame => ({ type: TYPE.windowUpdate, flags: 0, streamId, length: delta });+export const dataFrame = (streamId: number, data: Uint8Array, flags = 0): Frame => ({ type: TYPE.data, flags, streamId, length: data.length, data });+export const pingFrame = (value: number, flags: number = FLAG.syn): Frame => ({ type: TYPE.ping, flags, streamId: 0, length: value >>> 0 });+export const goAwayFrame = (code: number): Frame => ({ type: TYPE.goAway, flags: 0, streamId: 0, length: code });++/** The phone opens every stream; the computer only accepts. */+export type Role = "phone" | "computer";++interface StreamState {+ /** The phone side: false until the computer's ACK arrives. The computer side: false until accept(). */+ established: boolean;+ /** What the peer may still send before this side grants more. */+ receiveWindow: number;+ /** What this side may still send. */+ sendWindow: number;+ /** Consumed but not yet granted back. */+ uncredited: number;+ localFin: boolean;+ remoteFin: boolean;+}++export interface MuxEvents {+ /** Every frame to seal and send, in order. */+ send(frame: Frame): void;+ /** The computer side: a new stream. Answer with accept() or reset(); data may arrive first. */+ opened?(streamId: number): void;+ /** The phone side: the computer accepted. */+ accepted?(streamId: number): void;+ data(streamId: number, data: Uint8Array): void;+ /** The peer may send no more (FIN). */+ ended(streamId: number): void;+ /** Ended by RST from either side, or the session closing. */+ reset(streamId: number): void;+ /** The peer granted more send window. */+ writable(streamId: number): void;+ goAway?(code: number): void;+ pong?(value: number): void;+}++/** A frame that breaks the profile throws YamuxError. The caller then sends GoAway(1) through+ * `protocolError()` and closes the WebSocket with 4000. */+export class Mux {+ readonly role: Role;+ readonly #events: MuxEvents;+ readonly #streams = new Map<number, StreamState>();+ /** The highest ID the phone has opened. */+ #highestId = 0;+ #peerGoneAway = false;+ #localGoneAway = false;++ constructor(role: Role, events: MuxEvents) {+ this.role = role;+ this.#events = events;+ }++ get activeStreams(): number {+ return this.#streams.size;+ }++ get peerGoneAway(): boolean {+ return this.#peerGoneAway;+ }++ has(streamId: number): boolean {+ return this.#streams.has(streamId);+ }++ sendWindow(streamId: number): number {+ return this.#streams.get(streamId)?.sendWindow ?? 0;+ }++ /** The phone side. Data may follow at once, within the first 256 KiB. */+ open(): number {+ if (this.role !== "phone") throw new YamuxError("computer_open");+ if (this.#localGoneAway || this.#peerGoneAway) throw new YamuxError("gone_away");+ if (this.#streams.size >= MAX_STREAMS) throw new YamuxError("too_many_streams");+ const streamId = this.#highestId === 0 ? 1 : this.#highestId + 2;+ if (streamId > MAX_STREAM_ID) throw new YamuxError("ids_exhausted");+ this.#highestId = streamId;+ this.#streams.set(streamId, {+ established: false,+ receiveWindow: INITIAL_WINDOW + OPEN_WINDOW_DELTA,+ sendWindow: INITIAL_WINDOW,+ uncredited: 0,+ localFin: false,+ remoteFin: false,+ });+ this.#events.send(openFrame(streamId));+ return streamId;+ }++ /** The computer side, once the origin socket is connected. */+ accept(streamId: number): void {+ const stream = this.#streams.get(streamId);+ if (!stream || stream.established || this.role !== "computer") return;+ stream.established = true;+ stream.receiveWindow += OPEN_WINDOW_DELTA;+ this.#events.send(acceptFrame(streamId));+ }++ /** Sends up to the window and the frame cap; returns the bytes taken. */+ write(streamId: number, data: Uint8Array): number {+ const stream = this.#streams.get(streamId);+ if (!stream || stream.localFin || (this.role === "computer" && !stream.established)) return 0;+ const size = Math.min(data.length, stream.sendWindow, MAX_DATA_PAYLOAD);+ if (size === 0) return 0;+ stream.sendWindow -= size;+ this.#events.send(dataFrame(streamId, data.subarray(0, size)));+ return size;+ }++ finish(streamId: number): void {+ const stream = this.#streams.get(streamId);+ if (!stream || stream.localFin) return;+ stream.localFin = true;+ this.#events.send(finFrame(streamId));+ this.#closeIfDone(streamId, stream);+ }++ reset(streamId: number): void {+ if (!this.#streams.delete(streamId)) return;+ this.#events.send(resetFrame(streamId));+ this.#events.reset(streamId);+ }++ /** The receiver handed `bytes` on (to the origin socket, or the HTTP stack). Grants them back in 1 MiB steps. */+ consumed(streamId: number, bytes: number): void {+ const stream = this.#streams.get(streamId);+ if (!stream || stream.remoteFin) return;+ stream.uncredited += bytes;+ if (stream.uncredited < WINDOW_UPDATE_AFTER) return;+ const delta = stream.uncredited;+ stream.uncredited = 0;+ stream.receiveWindow += delta;+ this.#events.send(windowFrame(streamId, delta));+ }++ ping(value: number): void {+ this.#events.send(pingFrame(value));+ }++ goAway(code: number = GO_AWAY.normal): void {+ this.#localGoneAway = true;+ this.#events.send(goAwayFrame(code));+ }++ /** Sends GoAway(1); the caller closes with 4000. */+ protocolError(): void {+ this.goAway(GO_AWAY.protocol);+ this.closeAll();+ }++ closeAll(): void {+ const ids = [...this.#streams.keys()];+ this.#streams.clear();+ for (const id of ids) this.#events.reset(id);+ }++ receive(frame: Frame): void {+ if (frame.type === TYPE.ping) {+ if (frame.flags === FLAG.syn) this.#events.send(pingFrame(frame.length, FLAG.ack));+ else this.#events.pong?.(frame.length);+ return;+ }+ if (frame.type === TYPE.goAway) {+ this.#peerGoneAway = true;+ this.#events.goAway?.(frame.length);+ return;+ }+ if (frame.flags & FLAG.syn) {+ this.#receiveOpen(frame);+ return;+ }+ if (frame.flags & FLAG.ack) {+ this.#receiveAck(frame);+ return;+ }+ const stream = this.#known(frame.streamId);+ if (!stream) return;+ this.#receiveOnStream(frame.streamId, stream, frame);+ }++ /** A stream that ended is ignored: an RST and the peer's last frames cross. An ID never opened is an error. */+ #known(streamId: number): StreamState | null {+ if (streamId % 2 === 0 || streamId > this.#highestId) throw new YamuxError("unknown_stream");+ return this.#streams.get(streamId) ?? null;+ }++ #receiveOpen(frame: Frame): void {+ if (this.role === "phone") throw new YamuxError("computer_opened_stream");+ if (frame.type !== TYPE.windowUpdate || frame.flags !== FLAG.syn) throw new YamuxError("open_flags");+ if (frame.streamId % 2 === 0) throw new YamuxError("even_stream");+ if (frame.streamId <= this.#highestId) throw new YamuxError("stream_reused");+ this.#highestId = frame.streamId;+ if (this.#localGoneAway || this.#streams.size >= MAX_STREAMS) {+ this.#events.send(resetFrame(frame.streamId));+ return;+ }+ this.#streams.set(frame.streamId, {+ established: false,+ receiveWindow: INITIAL_WINDOW,+ sendWindow: INITIAL_WINDOW + frame.length,+ uncredited: 0,+ localFin: false,+ remoteFin: false,+ });+ this.#events.opened?.(frame.streamId);+ }++ #receiveAck(frame: Frame): void {+ if (this.role === "computer") throw new YamuxError("phone_ack");+ if (frame.type !== TYPE.windowUpdate || (frame.flags & ~(FLAG.ack | FLAG.fin | FLAG.rst)) !== 0) throw new YamuxError("ack_flags");+ const stream = this.#known(frame.streamId);+ if (!stream) return;+ if (stream.established) throw new YamuxError("duplicate_ack");+ stream.established = true;+ this.#events.accepted?.(frame.streamId);+ this.#receiveOnStream(frame.streamId, stream, { ...frame, flags: frame.flags & ~FLAG.ack });+ }++ #receiveOnStream(streamId: number, stream: StreamState, frame: Frame): void {+ if (frame.flags & FLAG.rst) {+ this.#streams.delete(streamId);+ this.#events.reset(streamId);+ return;+ }+ if (frame.type === TYPE.data) {+ if (stream.remoteFin && (frame.length > 0 || frame.flags & FLAG.fin)) throw new YamuxError("data_after_fin");+ if (frame.length > stream.receiveWindow) throw new YamuxError("window_exceeded");+ stream.receiveWindow -= frame.length;+ if (frame.length > 0) this.#events.data(streamId, frame.data as Uint8Array);+ } else if (frame.length > 0) {+ stream.sendWindow += frame.length;+ this.#events.writable(streamId);+ }+ if (frame.flags & FLAG.fin) {+ if (stream.remoteFin) throw new YamuxError("data_after_fin");+ stream.remoteFin = true;+ this.#events.ended(streamId);+ this.#closeIfDone(streamId, stream);+ }+ }++ #closeIfDone(streamId: number, stream: StreamState): void {+ if (stream.localFin && stream.remoteFin) this.#streams.delete(streamId);+ }+}diff --git a/connector/test/agent.test.ts b/connector/test/agent.test.tsindex 664e3b686a..67e2344223 100644--- a/connector/test/agent.test.ts+++ b/connector/test/agent.test.ts@@ -1,13 +1,20 @@+import { createServer, type Server } from "node:http";+import { createConnection, type AddressInfo } from "node:net";+import type { Duplex } from "node:stream";+import { afterEach, describe, expect, it } from "vitest";-import { Agent, backoffMs, connectUrl } from "../src/agent.ts";+import { Agent, backoffMs, connectUrl, savedConfig, transferAuthorization, type Refusal } from "../src/agent.ts";+import type { AuditEvent } from "../src/audit.ts";import { adminOrigin, enroll } from "../src/enroll.ts";-import { CLOSE_UNAUTHORIZED, type HostFacts, type Job, type JobReply } from "../src/protocol.ts";-import type { StatusRecord } from "../src/state.ts";+import { serveRequest } from "../src/home-requests.ts";+import { CLOSE_KEY_COPIED, CLOSE_UNAUTHORIZED, type ConfigPayload, type HostFacts, type Job, type JobReply } from "../src/protocol.ts";+import { generateKeyPair, unseal } from "../src/signed.ts";+import type { AgentRecord, ConfigRecord, StatusRecord } from "../src/state.ts";import { FakeAdmin } from "./fake-admin.ts";const host: HostFacts = { os: "Ubuntu 24.04.3 LTS", kernel: "6.8.0", arch: "x86_64", cpus: 4, memMb: 16_000, diskGb: 120, docker: "28.0.4", apparmor: true, userns: true };-const connector = { version: "1.0.0", protocol: 1 as const, image: null };+const connector = { version: "1.0.0", protocol: 2 as const, image: null };const cleanups: (() => Promise<void> | void)[] = [];afterEach(async () => {for (const cleanup of cleanups.splice(0).reverse()) await cleanup();@@ -21,113 +28,299 @@ async function until(check: () => boolean, ms = 5_000): Promise<void> {}}-async function connected(options: { handle?: (job: Job) => Promise<JobReply | null>; setTimer?: (callback: () => void, ms: number) => unknown } = {}) {+async function fakeAdmin(): Promise<FakeAdmin> {const admin = new FakeAdmin();- const origin = await admin.listen();+ await admin.listen();cleanups.push(() => admin.close());- const record = await enroll({ admin: origin, code: admin.mintCode(), host, connector });- const handled: Job[] = [];- const statuses: Partial<StatusRecord>[] = [];- const lines: string[] = [];- const agent = new Agent({- admin: origin, token: record.agentToken, log: (line) => lines.push(line), heartbeatMs: 100, random: () => 0,+ return admin;+}++interface AgentFixture {+ agent: Agent;+ record: { current: AgentRecord };+ count: { value: number };+ handled: Job[];+ statuses: Partial<StatusRecord>[];+ lines: string[];+ refusals: Refusal[];+ audits: AuditEvent[];+ saved: { config: ConfigRecord | null };+ retries: number[];+}++function makeConnector(record: AgentRecord, options: {+ handle?: (job: Job) => Promise<JobReply | null>; count?: { value: number }; now?: () => number; homePort?: () => number; deadMs?: number; pingMs?: number;+} = {}): AgentFixture {+ const fixture: AgentFixture = {+ agent: null as unknown as Agent, record: { current: record }, count: options.count ?? { value: 0 }, handled: [], statuses: [], lines: [], refusals: [], audits: [],+ saved: { config: null }, retries: [],+ };+ fixture.agent = new Agent({+ identity: () => fixture.record.current, log: (line) => fixture.lines.push(line), heartbeatMs: 100, random: () => 0, now: options.now,+ nextCount: () => ++fixture.count.value,+ saveAdminKeys: (keys) => { fixture.record.current = { ...fixture.record.current, adminKeys: keys }; },+ config: { saved: () => fixture.saved.config, save: (config) => { fixture.saved.config = config; } },heartbeat: async () => ({ heartbeat: { host: { ...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0, checks: [] }, home: { state: "running", image: null, health: null }, connector } }),handle: options.handle ?? (async (job) => {- handled.push(job);+ fixture.handled.push(job);return { id: job.id, ok: true, result: { host: { ...host } } } as unknown as JobReply;}),- status: (patch) => statuses.push(patch),- ...(options.setTimer ? { setTimer: options.setTimer } : {}),+ stream: (stream, accept) => serveRequest(stream, accept, {+ connectHome: () => new Promise<Duplex>((resolve, reject) => {+ const socket = createConnection({ host: "127.0.0.1", port: options.homePort?.() ?? 9 });+ socket.once("connect", () => resolve(socket));+ socket.once("error", reject);+ }),+ record: (event) => fixture.audits.push(event),+ }),+ refused: (refusal) => fixture.refusals.push(refusal),+ status: (patch) => fixture.statuses.push(patch),+ // Every wait of a second or more (a retry, the handshake deadline, a ping) passes in 30 ms; each is recorded.+ setTimer: (callback, ms) => {+ fixture.retries.push(ms);+ return setTimeout(callback, ms >= 1000 ? 30 : ms);+ },+ ...(options.deadMs ? { deadMs: options.deadMs } : {}),+ ...(options.pingMs ? { pingMs: options.pingMs } : {}),});- cleanups.push(() => agent.stop());- agent.start();- await until(() => admin.connected);- return { admin, origin, record, agent, handled, statuses, lines };+ cleanups.push(() => fixture.agent.stop());+ return fixture;+}++async function connected(options: Parameters<typeof makeConnector>[1] & { accepted?: boolean } = {}) {+ const admin = await fakeAdmin();+ const record = await enroll({ admin: admin.origin, code: admin.mintCode(), host, connector });+ if (options.accepted) admin.boxes.get(record.boxId)!.state = "accepted";+ const fixture = makeConnector(record, options);+ fixture.agent.start();+ await until(() => fixture.agent.connected);+ return { admin, ...fixture };}describe("the connector's connection to MausBot", () => {- it("enrols once with the one-time code, then connects with its own token and sends a heartbeat every interval", async () => {- const { admin, record, statuses, lines } = await connected();- const [server] = admin.servers.values();- expect(server).toMatchObject({ serverId: record.serverId, cloudId: record.cloudId, token: record.agentToken, enroll: { host, connector } });- expect(record).toMatchObject({ version: 1, admin: admin.origin });+ it("enrols once with the one-time code and a key it made, pins the Admin's keys, and proves its key on every connection", async () => {+ const { admin, record, statuses, lines, agent } = await connected();+ const box = admin.boxes.get(record.current.boxId)!;+ expect(box).toMatchObject({ publicKey: record.current.publicKey, state: "pending", enroll: { host, connector, publicKey: record.current.publicKey } });+ expect(record.current).toMatchObject({ version: 2, admin: admin.origin, teamId: box.teamId, adminKeys: admin.publicKeys });+ expect(agent.state).toBe("pending");await until(() => admin.heartbeats.length >= 3);- expect(admin.heartbeats[0]).toMatchObject({ home: { state: "running" }, connector: { protocol: 1 }, host: { arch: "x86_64" } });+ expect(admin.heartbeats[0]).toMatchObject({ home: { state: "running" }, connector: { protocol: 2 }, host: { arch: "x86_64" } });expect(statuses).toContainEqual(expect.objectContaining({ connected: true, unauthorized: false }));- expect(admin.connections).toHaveLength(1);- expect(lines.join("\n")).not.toContain(record.agentToken);+ expect(statuses).toContainEqual({ boxState: "pending" });+ admin.drop();+ await until(() => admin.connections.length === 2 && agent.connected);+ expect(admin.connections.map((connection) => connection.count)).toEqual([1, 2]);+ expect(lines.join("\n")).not.toContain(record.current.privateKey);+ expect(lines).toContain("connected to MausBot (waiting for the team's Owner to accept this server)");await expect(enroll({ admin: admin.origin, code: [...admin.codes][0] ?? "MB-USED-CODE", host, connector })).rejects.toThrow("This code isn't valid anymore: a code works once, for one hour. Make a new one in MausBot and run the install command again.");});- it("answers each job once: the same id again gets the same reply, and never a second run", async () => {- const { admin, handled } = await connected();- const first = await admin.job("host-health", {}, "job-1");- expect(first).toMatchObject({ id: "job-1", ok: true });- const again = await admin.job("host-health", {}, "job-1");- expect(again).toEqual(first);- expect(handled.map((job) => job.id)).toEqual(["job-1"]);+ it("drops a connection whose hello no key it pinned signed, and never takes a job on it", async () => {+ const admin = await fakeAdmin();+ const record = await enroll({ admin: admin.origin, code: admin.mintCode(), host, connector });+ admin.impostor = generateKeyPair();+ const fixture = makeConnector(record);+ fixture.agent.start();+ await until(() => admin.connections.length >= 2);+ expect(fixture.agent.connected).toBe(false);+ expect(fixture.statuses).not.toContainEqual(expect.objectContaining({ connected: true }));+ expect(fixture.statuses).toContainEqual({ lastError: `the MausBot at ${admin.origin} did not prove it holds MausBot's key (the signature does not verify)` });+ expect(fixture.lines).toContain("dropping the connection to MausBot: MausBot's hello did not verify: the signature does not verify");+ admin.impostor = null;+ await until(() => fixture.agent.connected);});- it("refuses a malformed job by its id, and ignores what has no id or is not JSON", async () => {- const { admin, handled, lines } = await connected();- expect(await admin.job("shell" as "status", { command: "id" }, "job-2")).toEqual({ id: "job-2", ok: false, error: { code: "unknown_job", message: 'unknown job type "shell"' } });- expect(await admin.job("restore", { backupId: "../../etc" }, "job-3")).toMatchObject({ id: "job-3", ok: false, error: { code: "invalid_args" } });- admin.send({ type: "status" });- admin.send("not json");- await until(() => lines.some((line) => line.includes("not JSON")));- expect(lines).toContain("ignored a job without a valid id: a job needs an id of 1 to 64 letters, digits, - or _");- expect(handled).toEqual([]);+ it("runs a job only when the Admin signed it for this box and it is fresh by the Admin's clock, whatever this server's clock says", async () => {+ const { admin, record, handled, refusals } = await connected({ accepted: true, now: () => Date.now() - 3 * 3600_000 });+ expect((await admin.job("host-health", {}, "signed-1")).ok).toBe(true);+ expect(handled.map((job) => job.id)).toEqual(["signed-1"]);++ admin.send({ id: "bare-1", type: "stop", args: {} });+ expect(await admin.job("host-health", {}, "wrong-box-1", { box: "box_someoneelse0" })).toMatchObject({ ok: false, error: { code: "wrong_box" } });+ expect(await admin.job("host-health", {}, "old-1", { ageMs: 16 * 60_000 })).toMatchObject({ ok: false, error: { code: "expired_job" } });+ admin.send({ job: admin.signJob(record.current.boxId, { id: "stranger-1", type: "stop", args: {} }, { key: generateKeyPair() }) });+ admin.send({ job: "not.an-envelope" });+ expect((await admin.job("status", {}, "signed-2")).ok).toBe(true);+ expect(handled.map((job) => job.id)).toEqual(["signed-1", "signed-2"]);+ expect(refusals).toEqual([+ { code: "unsigned_job", message: "a job MausBot did not sign" },+ { code: "wrong_box", message: "the job was signed for another server", id: "wrong-box-1", type: "host-health" },+ { code: "expired_job", message: "the job's signature is too old", id: "old-1", type: "host-health" },+ { code: "unsigned_job", message: "a job MausBot did not sign (the signature does not verify)" },+ { code: "unsigned_job", message: "a job MausBot did not sign (not an envelope)" },+ ]);+ expect(admin.replies.map((reply) => reply.id)).not.toContain("bare-1");+ expect(admin.replies.map((reply) => reply.id)).not.toContain("stranger-1");+ });++ it("keeps a server the team's Owner has not accepted to jobs that only read, until the Owner accepts it", async () => {+ const { admin, record, handled, agent } = await connected();+ expect((await admin.job("status", {}, "read-1")).ok).toBe(true);+ expect(await admin.job("stop", {}, "stop-1")).toEqual({ id: "stop-1", ok: false, error: { code: "pending_box", message: "The team's Owner has not accepted this server in MausBot yet." } });+ admin.accept(record.current.boxId);+ await until(() => agent.state === "accepted");+ expect((await admin.job("stop", {}, "stop-2")).ok).toBe(true);+ expect(handled.map((job) => job.id)).toEqual(["read-1", "stop-2"]);+ });++ it("answers each job once: the same id again gets the same reply, and never a second run", async () => {+ const { admin, handled } = await connected({ accepted: true });+ const first = await admin.job("host-health", {}, "same-id");+ admin.send({ job: admin.signJob(admin.liveBox!, { id: "same-id", type: "host-health", args: {} }) });+ await until(() => (admin.replyCounts.get("same-id") ?? 0) >= 2);+ expect(handled).toHaveLength(1);+ expect(admin.replies.filter((reply) => reply.id === "same-id")).toEqual([first]);});it("keeps a reply made while the connection is down, comes back with backoff, and delivers it", async () => {- let finish: (reply: JobReply) => void = () => {};- const { admin } = await connected({ handle: (job) => new Promise((resolve) => { finish = resolve; void job; }) });- admin.send({ id: "slow-1", type: "update", args: { image: `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"b".repeat(64)}` } });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const { admin, retries, agent } = await connected({ accepted: true, handle: async (job) => {+ await gate;+ return { id: job.id, ok: true, result: { host: { ...host } } } as unknown as JobReply;+ } });+ const reply = admin.replyTo("slow-1");+ admin.send({ job: admin.signJob(admin.liveBox!, { id: "slow-1", type: "host-health", args: {} }) });await new Promise((resolve) => setTimeout(resolve, 50));admin.drop();- await until(() => !admin.connected);- finish({ id: "slow-1", ok: false, error: { code: "update_rolled_back", message: "rolled back", image: "x" } });- const reply = await admin.replyTo("slow-1", 5_000);- expect(reply).toMatchObject({ id: "slow-1", ok: false, error: { code: "update_rolled_back" } });- expect(admin.connections).toHaveLength(2);- // Acknowledged: a later connection does not bring it again.- const count = admin.replyCounts.get("slow-1");+ await until(() => !agent.connected);+ release();+ await until(() => agent.connected);+ expect((await reply).ok).toBe(true);+ expect(retries).toContain(backoffMs(0, 0));+ });++ it("loses its connection the moment its key is revoked, then slows right down and says why", async () => {+ const { admin, record, statuses, lines, retries } = await connected({ accepted: true });+ admin.revoke(record.current.boxId);+ await until(() => statuses.some((status) => status.unauthorized === true));+ expect(admin.closes).toEqual([{ boxId: record.current.boxId, code: CLOSE_UNAUTHORIZED }]);+ expect(statuses).toContainEqual({ connected: false, unauthorized: true, lastError: "MausBot no longer knows this server" });+ expect(lines).toContain("MausBot no longer knows this server; run the install command again with a new code to connect it");+ expect(retries).toContain(5 * 60_000);+ });++ it("a copy of the key gives itself away by its connection count: the Admin revokes the key, and both servers are shut out", async () => {+ const { admin, record, agent, count, statuses } = await connected({ accepted: true });+ // A disk copy taken now: the same key, the same count on disk.+ const copy = makeConnector(record.current, { count: { value: count.value - 1 } });+ copy.agent.start();+ await until(() => admin.boxes.get(record.current.boxId)!.revoked === "copied");+ await until(() => statuses.some((status) => status.unauthorized === true) && copy.statuses.some((status) => status.unauthorized === true));+ expect(agent.connected).toBe(false);+ expect(copy.agent.connected).toBe(false);+ expect(admin.closes).toContainEqual({ boxId: record.current.boxId, code: CLOSE_KEY_COPIED });+ for (const status of [...statuses, ...copy.statuses].filter((entry) => entry.unauthorized)) {+ expect(status.lastError).toBe("MausBot saw another server use this server's key, so it stopped trusting the key");+ }+ });++ it("keeps the Admin's newest signed schedule and policy on its disk, and only those it can verify", async () => {+ const { admin, record, saved, agent } = await connected({ accepted: true });+ await until(() => agent.state === "accepted");+ const box = record.current.boxId;+ admin.sendConfig(box, { version: 3, policy: { offlineHours: 48 } });+ await until(() => saved.config?.version === 3);+ admin.sendConfig(box, { version: 2, policy: { offlineHours: 1 } });+ admin.send({ config: "forged.config" });+ await admin.job("status", {});+ expect(saved.config?.version).toBe(3);+ const kept = savedConfig(saved.config, record.current) as ConfigPayload;+ expect(kept).toMatchObject({ version: 3, state: "accepted", policy: { offlineHours: 48 }, schedule: { ring: "standard", window: { timeZone: "Europe/Berlin" } } });+ const [body, signature] = saved.config!.envelope.split(".");+ const tampered = Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(body!, "base64url").toString("utf8")), policy: { offlineHours: 720 } })).toString("base64url");+ expect(savedConfig({ ...saved.config!, envelope: `${tampered}.${signature}` }, record.current)).toBeNull();+ expect(savedConfig(saved.config, { ...record.current, boxId: "box_another00000" })).toBeNull();+ });++ it("pins the Admin's new keys only from a hello one of its pinned keys signed", async () => {+ const { admin, record, agent } = await connected({ accepted: true });+ const next = generateKeyPair();+ admin.keys.k2 = next;+ admin.announce = { k1: admin.keys.k1!.publicKey, k2: next.publicKey };+ admin.drop();+ await until(() => Object.keys(record.current.adminKeys).length === 2);+ admin.signingKid = "k2";admin.drop();- await until(() => admin.connections.length === 3);- await new Promise((resolve) => setTimeout(resolve, 100));- expect(admin.replyCounts.get("slow-1")).toBe(count);- expect(backoffMs(0, 0)).toBe(500);- expect(backoffMs(3, 1)).toBe(12_000);- expect(backoffMs(20, 0.5)).toBe(60_000);- });-- it("slows right down when MausBot no longer knows its token, and says so", async () => {- const waits: number[] = [];- const { admin, record, statuses, lines } = await connected({- setTimer: (callback, ms) => {- waits.push(ms);- return ms < 1000 ? setTimeout(callback, ms) : setTimeout(() => {}, 0);- },+ await until(() => admin.connections.length === 3 && agent.connected);+ expect((await admin.job("host-health", {})).ok).toBe(true);+ });++ it("carries the Admin's requests to the home and nowhere else, one per stream, each written to the audit log", async () => {+ const seen: { method: string; url: string; host: string; body: string }[] = [];+ const home: Server = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (chunk: Buffer) => chunks.push(chunk));+ req.on("end", () => {+ seen.push({ method: req.method!, url: req.url!, host: req.headers.host!, body: Buffer.concat(chunks).toString("utf8") });+ res.writeHead(req.url === "/api/cloud/pairing" ? 200 : 204, { "content-type": "application/json" }).end(req.url === "/api/cloud/pairing" ? '{"code":"SECRET-PAIRING-CODE"}' : undefined);+ });});- admin.revoked.add(record.agentToken);- admin.drop();- await until(() => statuses.some((patch) => patch.unauthorized === true));- expect(waits).toContain(5 * 60_000);- expect(lines).toContain("MausBot no longer knows this server; run the install command again with a new code to connect it");- expect(CLOSE_UNAUTHORIZED).toBe(4401);+ await new Promise<void>((resolve) => home.listen(0, "127.0.0.1", resolve));+ cleanups.push(() => new Promise<void>((resolve) => home.close(() => resolve())));+ let port = (home.address() as AddressInfo).port;+ const { admin, audits } = await connected({ accepted: true, homePort: () => port });+ expect(await admin.fetch("/api/cloud/health?x=1", { host: "mausbot.acme.example" })).toEqual({ status: 204, body: "" });+ const claim = JSON.stringify({ label: "Ada's laptop", member: { email: "[email protected]", role: "admin" } });+ expect(await admin.fetch("/api/cloud/pairing", { method: "POST", body: claim, host: "mausbot.acme.example" })).toEqual({ status: 200, body: '{"code":"SECRET-PAIRING-CODE"}' });+ expect(seen).toEqual([+ { method: "GET", url: "/api/cloud/health?x=1", host: "mausbot.acme.example", body: "" },+ { method: "POST", url: "/api/cloud/pairing", host: "mausbot.acme.example", body: claim },+ ]);+ port = 9;+ expect(await admin.fetch("/api/cloud/health")).toEqual({ status: 502, body: "" });+ expect(audits).toEqual([+ { event: "request", by: "admin", method: "GET", path: "/api/cloud/health", status: 204 },+ { event: "request", by: "admin", method: "POST", path: "/api/cloud/pairing", status: 200, member: { email: "[email protected]", role: "admin", device: "Ada's laptop" } },+ { event: "request", by: "admin", method: "GET", path: "/api/cloud/health", status: 502 },+ ]);+ expect(JSON.stringify(audits)).not.toContain("SECRET-PAIRING-CODE");+ });++ it("comes back after the Admin's restart when the Admin said to, not at once", async () => {+ const { admin, agent, retries } = await connected({ accepted: true });+ admin.restarting(4000, 0);+ await until(() => !agent.connected);+ await until(() => retries.includes(4000));+ await until(() => agent.connected);+ });++ it("drops a connection the Admin went silent on, and opens a new one", async () => {+ const { admin, agent, lines } = await connected({ accepted: true, pingMs: 50, deadMs: 300 });+ admin.freeze();+ await until(() => lines.includes("dropping the connection to MausBot: nothing from MausBot for 0 s"));+ await until(() => admin.connections.length === 2 && agent.connected);+ });++ it("signs a transfer token for one job that the Admin can check against the box's key", async () => {+ const { record } = await connected();+ const header = transferAuthorization(record.current, "export-7", 1_000);+ expect(header.startsWith("Box ")).toBe(true);+ const opened = unseal(header.slice(4), { box: record.current.publicKey });+ expect(opened).toEqual({ ok: true, payload: { t: "transfer", box: record.current.boxId, job: "export-7", iat: 1_000, exp: 601_000, kid: "box" } });+ expect(unseal(header.slice(4), { box: generateKeyPair().publicKey }).ok).toBe(false);});it("connects to the Admin's own origin over wss, and to a test Admin on loopback over ws only", () => {- expect(connectUrl("https://cloud.openmausbot.com")).toBe("wss://cloud.openmausbot.com/api/cloud/servers/agent/connect");- expect(connectUrl("http://127.0.0.1:9000")).toBe("ws://127.0.0.1:9000/api/cloud/servers/agent/connect");- expect(adminOrigin("https://cloud.openmausbot.com/")).toBe("https://cloud.openmausbot.com");- expect(adminOrigin("http://127.0.0.1:9000")).toBe("http://127.0.0.1:9000");- for (const bad of ["http://cloud.openmausbot.com", "https://user:[email protected]", "ftp://x", undefined]) expect(() => adminOrigin(bad)).toThrow();+ expect(connectUrl("https://cloud.example.test")).toBe("wss://cloud.example.test/api/cloud/box/v1/connect");+ expect(connectUrl("http://127.0.0.1:8123")).toBe("ws://127.0.0.1:8123/api/cloud/box/v1/connect");+ expect(adminOrigin("https://cloud.example.test/")).toBe("https://cloud.example.test");+ expect(() => adminOrigin("http://cloud.example.test")).toThrow("is not a MausBot address this connector may use.");+ expect(() => adminOrigin(undefined)).toThrow("The install command did not say which MausBot to connect to.");});it("says plainly when MausBot cannot be reached at enrolment", async () => {await expect(enroll({ admin: "http://127.0.0.1:9", code: "MB-1A2B-3C4D", host, connector })).rejects.toThrow(/^This server can't reach MausBot at http:\/\/127\.0\.0\.1:9 /);await expect(enroll({ admin: "http://127.0.0.1:9", code: "MB 1A2B", host, connector })).rejects.toThrow("the code is the one-time code MausBot shows next to the install command");});++ it("refuses a job before the handshake, and a binary message before it, by closing the connection", async () => {+ const { admin, agent } = await connected({ accepted: true });+ expect(agent.connected).toBe(true);+ admin.sendBinary(new Uint8Array([0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));+ await until(() => admin.connections.length === 2 && agent.connected);+ });});+diff --git a/connector/test/fake-admin.ts b/connector/test/fake-admin.tsindex 2b54807f39..a31f3137ac 100644--- a/connector/test/fake-admin.ts+++ b/connector/test/fake-admin.ts@@ -1,42 +1,75 @@// A stand-in for the MausBot Cloud Admin's side of the connector protocol (connector/src/protocol.ts): one-time codes,-// enrolment, the agent WebSocket with its Bearer token, heartbeats, jobs and their replies, and export uploads. The-// unit tests drive it in process; the e2e runs it as a program and drives it over its /control routes on loopback:+// enrolment with the box's key, the channel's handshake (challenge, the box's signed auth with its connection count,+// the Admin's signed hello), signed jobs and their replies, signed configs, HTTP requests to the home over yamux+// streams, revocation and export uploads. The unit tests drive it in process; the e2e runs it as a program and drives it+// over its /control routes on loopback:// node connector/test/fake-admin.ts <port> <code>import { randomBytes } from "node:crypto";-import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import { createServer, request, type IncomingMessage, type Server, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { fileURLToPath } from "node:url";import { WebSocketServer, type WebSocket } from "ws";+import { MuxSession } from "../src/mux.ts";import {- CLOSE_REPLACED, CLOSE_UNAUTHORIZED, CONNECT_PATH, ENROLL_PATH, EXPORT_PATH,- type EnrollRequest, type EnrollResponse, type Heartbeat, type JobReply, type JobType, type JobArgs,+ CHANNEL_PROTOCOL, CLOSE_KEY_COPIED, CLOSE_PROTOCOL, CLOSE_REPLACED, CLOSE_UNAUTHORIZED, CONNECT_PATH, ENROLL_PATH, EXPORT_PATH, JOB_LIFETIME_MS, TRANSFER_SCHEME,+ authText, type BoxState, type ConfigPayload, type EnrollRequest, type EnrollResponse, type Heartbeat, type JobArgs, type JobReply, type JobType,} from "../src/protocol.ts";+import { b64u, generateKeyPair, seal, unseal, verifyText, type KeyPair } from "../src/signed.ts";-interface EnrolledServer {- serverId: string;- cloudId: string;- token: string;+export interface FakeBox {+ boxId: string;+ teamId: string;+ publicKey: string;+ state: BoxState;+ count: number;+ revoked: "revoked" | "copied" | null;enroll: EnrollRequest;}+interface Live {+ ws: WebSocket;+ boxId: string;+ mux: MuxSession;+}++export interface JobOptions {+ /** Sign it for this box instead (to prove the box refuses it). */+ box?: string;+ /** Send it bare, not signed. */+ unsigned?: boolean;+ /** Sign it with this key instead of the Admin's. */+ key?: KeyPair;+ /** Signed this long ago. */+ ageMs?: number;+ timeoutMs?: number;+}+export class FakeAdmin {readonly codes = new Set<string>();- readonly servers = new Map<string, EnrolledServer>();+ readonly boxes = new Map<string, FakeBox>();readonly heartbeats: Heartbeat["heartbeat"][] = [];readonly replies: JobReply[] = [];/** Every reply message per job id, repeats included. */readonly replyCounts = new Map<string, number>();readonly exports = new Map<string, Buffer>();- readonly connections: { token: string; at: number }[] = [];- /** Tokens the Admin forgot: their next connection is closed with 4401. */- readonly revoked = new Set<string>();- private socket: WebSocket | null = null;+ readonly connections: { boxId: string; count: number; at: number }[] = [];+ readonly closes: { boxId: string; code: number }[] = [];+ /** The Admin's signing keys by id; `hello` signs with `signingKid`. */+ readonly keys: Record<string, KeyPair> = { k1: generateKeyPair() };+ signingKid = "k1";+ /** Sign every hello with this key instead (a stranger pretending to be the Admin). */+ impostor: KeyPair | null = null;+ /** Keys to announce in the next hello (rotation). */+ announce: Record<string, string> | null = null;+ clockOffsetMs = 0;+ private live: Live | null = null;private readonly waiting = new Map<string, (reply: JobReply) => void>();private readonly http: Server;private readonly wss: WebSocketServer;private nextJob = 1;+ private configVersion = 0;constructor() {this.http = createServer((req, res) => {@@ -44,27 +77,13 @@ export class FakeAdmin {res.writeHead(500).end(String(error));});});- this.wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });+ this.wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024, handleProtocols: (offered) => (offered.has(CHANNEL_PROTOCOL) ? CHANNEL_PROTOCOL : false) });this.http.on("upgrade", (req, socket, head) => {if (new URL(req.url ?? "/", "http://admin").pathname !== CONNECT_PATH) {socket.destroy();return;}- const token = /^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1] ?? "";- this.wss.handleUpgrade(req, socket, head, (ws) => {- const known = [...this.servers.values()].some((server) => server.token === token);- if (!known || this.revoked.has(token)) {- ws.close(CLOSE_UNAUTHORIZED, "unknown token");- return;- }- this.connections.push({ token, at: Date.now() });- this.socket?.close(CLOSE_REPLACED, "a newer connection took over");- this.socket = ws;- ws.on("message", (data) => this.received(String(data)));- ws.on("close", () => {- if (this.socket === ws) this.socket = null;- });- });+ this.wss.handleUpgrade(req, socket, head, (ws) => this.handshake(ws));});}@@ -78,7 +97,15 @@ export class FakeAdmin {}get connected(): boolean {- return this.socket !== null && this.socket.readyState === 1;+ return this.live !== null && this.live.ws.readyState === 1;+ }++ get liveBox(): string | null {+ return this.connected ? this.live!.boxId : null;+ }++ get publicKeys(): Record<string, string> {+ return Object.fromEntries(Object.entries(this.keys).map(([kid, key]) => [kid, key.publicKey]));}mintCode(code = `MB-${randomBytes(4).toString("hex").toUpperCase()}-${randomBytes(4).toString("hex").toUpperCase()}`): string {@@ -94,29 +121,87 @@ export class FakeAdmin {/** Drops the connection as a network failure would. */drop(): void {- this.socket?.terminate();- this.socket = null;+ this.live?.mux.close();+ this.live?.ws.terminate();+ this.live = null;+ }++ /** Stops reading the connection, as a network that went quiet would. */+ freeze(): void {+ this.live?.ws.pause();+ }++ /** The team's Owner accepted the box: a signed config says so at once. */+ accept(boxId: string): void {+ this.boxes.get(boxId)!.state = "accepted";+ if (this.live?.boxId === boxId) this.sendConfig(boxId);+ }++ /** Revokes the box's key and closes its connection at once, as the Admin does. */+ revoke(boxId: string, why: "revoked" | "copied" = "revoked"): void {+ this.boxes.get(boxId)!.revoked = why;+ if (this.live?.boxId === boxId) this.closeLive(why === "copied" ? CLOSE_KEY_COPIED : CLOSE_UNAUTHORIZED, why);}send(message: unknown): void {- if (!this.socket) throw new Error("no connector is connected");- this.socket.send(typeof message === "string" ? message : JSON.stringify(message));+ if (!this.live) throw new Error("no connector is connected");+ this.live.ws.send(typeof message === "string" ? message : JSON.stringify(message));+ }++ sendBinary(bytes: Uint8Array): void {+ this.live!.ws.send(bytes, { binary: true });+ }++ restarting(reconnectInMs: number, tryForMs: number): void {+ this.send({ t: "restarting", reconnectInMs, tryForMs });+ this.closeLive(1012, "restarting");+ }++ signJob(box: string, job: { id: string; type: string; args: unknown }, options: JobOptions = {}): string {+ const now = Date.now() + this.clockOffsetMs - (options.ageMs ?? 0);+ const key = options.key ?? this.keys[this.signingKid]!;+ return seal({ t: "job", box: options.box ?? box, iat: now, exp: now + JOB_LIFETIME_MS, job }, this.signingKid, key.privateKey);}/** Sends a job and resolves with the next reply to its id. */- job<T extends JobType>(type: T, args: JobArgs[T] | Record<string, unknown>, id = `job-${this.nextJob++}`, timeoutMs = 30 * 60_000): Promise<JobReply> {- const reply = new Promise<JobReply>((resolve, reject) => {- const timer = setTimeout(() => {- this.waiting.delete(id);- reject(new Error(`no reply to ${type} ${id}`));- }, timeoutMs);- this.waiting.set(id, (value) => {- clearTimeout(timer);- resolve(value);+ job<T extends JobType>(type: T, args: JobArgs[T] | Record<string, unknown>, id = `job-${this.nextJob++}`, options: JobOptions = {}): Promise<JobReply> {+ const reply = this.replyTo(id, options.timeoutMs ?? 30 * 60_000);+ const job = { id, type, args };+ this.send(options.unsigned ? job : { job: this.signJob(this.live!.boxId, job, options) });+ return reply;+ }++ sendConfig(boxId: string, patch: Partial<Pick<ConfigPayload, "schedule" | "policy">> & { version?: number } = {}): number {+ const version = patch.version ?? ++this.configVersion;+ this.configVersion = Math.max(this.configVersion, version);+ const payload: Omit<ConfigPayload, "kid"> = {+ t: "config", box: boxId, iat: Date.now() + this.clockOffsetMs, version, state: this.boxes.get(boxId)!.state,+ schedule: patch.schedule ?? { window: { days: [0], start: "02:00", end: "05:00", timeZone: "Europe/Berlin" }, ring: "standard", holdUntil: null, image: null },+ policy: patch.policy ?? { offlineHours: 72 },+ };+ this.send({ config: seal(payload, this.signingKid, this.keys[this.signingKid]!.privateKey) });+ return version;+ }++ /** One HTTP request to the home through the box, over a stream this side opens. */+ fetch(path: string, init: { method?: string; host?: string; body?: string; headers?: Record<string, string> } = {}): Promise<{ status: number; body: string }> {+ const live = this.live;+ if (!live) throw new Error("no connector is connected");+ return new Promise((resolve, reject) => {+ const body = init.body ?? "";+ const req = request({+ // No agent: Node then asks createConnection for the socket, here a stream through the box.+ method: init.method ?? "GET", path, createConnection: () => live.mux.openStream() as never,+ headers: { host: init.host ?? "home.example.test", connection: "close", ...(body ? { "content-type": "application/json", "content-length": String(Buffer.byteLength(body)) } : {}), ...init.headers },+ }, (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));+ res.on("error", reject);});+ req.on("error", reject);+ req.end(body || undefined);});- this.send({ id, type, args });- return reply;}/** The reply to a job id, whenever it arrives (a job answered after a reconnect, or by a new connector). */@@ -132,6 +217,55 @@ export class FakeAdmin {});}+ private closeLive(code: number, reason: string): void {+ const live = this.live;+ if (!live) return;+ this.live = null;+ live.mux.close();+ this.closes.push({ boxId: live.boxId, code });+ live.ws.close(code, reason);+ }++ private handshake(ws: WebSocket): void {+ const adminNonce = b64u(randomBytes(32));+ ws.send(JSON.stringify({ t: "challenge", v: 1, nonce: adminNonce }));+ ws.once("message", (data) => {+ let auth: { box?: string; count?: number; nonce?: string; sig?: string };+ try { auth = JSON.parse(String(data)) as typeof auth; } catch { return ws.close(CLOSE_PROTOCOL, "not JSON"); }+ const box = this.boxes.get(String(auth.box));+ if (!box || box.revoked) return ws.close(box?.revoked === "copied" ? CLOSE_KEY_COPIED : CLOSE_UNAUTHORIZED, "unknown box");+ if (typeof auth.count !== "number" || typeof auth.nonce !== "string" || typeof auth.sig !== "string"+ || !verifyText(box.publicKey, authText(box.boxId, adminNonce, auth.nonce, auth.count), auth.sig)) return ws.close(CLOSE_UNAUTHORIZED, "bad signature");+ if (auth.count <= box.count) {+ this.revoke(box.boxId, "copied");+ return ws.close(CLOSE_KEY_COPIED, "a copy of this key");+ }+ box.count = auth.count;+ this.closeLive(CLOSE_REPLACED, "a newer connection took over");+ const mux = new MuxSession("phone", {+ send: (frame) => ws.send(frame, { binary: true }),+ get bufferedAmount() { return ws.bufferedAmount; },+ onceDrained: (listener) => setTimeout(listener, 10),+ }, { failed: () => ws.close(CLOSE_PROTOCOL, "yamux") });+ const live: Live = { ws, boxId: box.boxId, mux };+ this.live = live;+ this.connections.push({ boxId: box.boxId, count: auth.count, at: Date.now() });+ const signer = this.impostor ?? this.keys[this.signingKid]!;+ ws.send(JSON.stringify({ t: "hello", signed: seal({+ t: "hello", box: box.boxId, adminNonce, boxNonce: auth.nonce, count: auth.count, now: Date.now() + this.clockOffsetMs, state: box.state,+ ...(this.announce ? { keys: this.announce } : {}),+ }, this.signingKid, signer.privateKey) }));+ ws.on("message", (message, binary) => {+ if (binary) return mux.receive(new Uint8Array(message as Buffer));+ this.received(String(message));+ });+ ws.on("close", () => {+ mux.close();+ if (this.live === live) this.live = null;+ });+ });+ }+private received(text: string): void {const message = JSON.parse(text) as Heartbeat | JobReply;if ("heartbeat" in message) {@@ -159,27 +293,44 @@ export class FakeAdmin {res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(value));}+ /** The box a transfer's `Authorization: Box …` names, when its signature and lifetime hold. */+ private transferBox(header: string | undefined, jobId: string): FakeBox | null {+ const envelope = header?.startsWith(`${TRANSFER_SCHEME} `) ? header.slice(TRANSFER_SCHEME.length + 1) : "";+ const claimed = /^([^.]+)\./.exec(envelope)?.[1];+ let boxId = "";+ try { boxId = String((JSON.parse(Buffer.from(claimed ?? "", "base64url").toString("utf8")) as { box?: unknown }).box); } catch { return null; }+ const box = this.boxes.get(boxId);+ if (!box || box.revoked) return null;+ const opened = unseal(envelope, { box: box.publicKey });+ if (!opened.ok || opened.payload.t !== "transfer" || opened.payload.job !== jobId || Number(opened.payload.exp) < Date.now()) return null;+ return box;+ }+private async route(req: IncomingMessage, res: ServerResponse): Promise<void> {const url = new URL(req.url ?? "/", "http://admin");if (req.method === "POST" && url.pathname === ENROLL_PATH) {let request: EnrollRequest;try { request = JSON.parse((await this.body(req)).toString("utf8")) as EnrollRequest; } catch { return this.json(res, 400, { error: "invalid_body" }); }if (!this.codes.delete(request.code)) return this.json(res, 401, { error: "invalid_code" });- const answer: EnrollResponse = { serverId: `srv_${randomBytes(6).toString("hex")}`, cloudId: `cloud_${randomBytes(6).toString("hex")}`, agentToken: `ombs_${randomBytes(32).toString("base64url")}` };- this.servers.set(answer.serverId, { ...answer, token: answer.agentToken, enroll: request });+ const answer: EnrollResponse = { boxId: `box_${randomBytes(8).toString("hex")}`, teamId: `team_${randomBytes(6).toString("hex")}`, adminKeys: this.publicKeys, state: "pending" };+ this.boxes.set(answer.boxId, { boxId: answer.boxId, teamId: answer.teamId, publicKey: request.publicKey, state: "pending", count: 0, revoked: null, enroll: request });return this.json(res, 200, answer);}if (req.method === "PUT" && url.pathname.startsWith(`${EXPORT_PATH}/`)) {- const token = /^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1] ?? "";- if (![...this.servers.values()].some((server) => server.token === token)) return this.json(res, 401, { error: "unauthorized" });- this.exports.set(url.pathname.slice(EXPORT_PATH.length + 1), await this.body(req));+ const jobId = url.pathname.slice(EXPORT_PATH.length + 1);+ if (!this.transferBox(req.headers.authorization, jobId)) return this.json(res, 401, { error: "unauthorized" });+ this.exports.set(jobId, await this.body(req));return this.json(res, 200, { ok: true });}// The e2e's handle on this Admin; never part of the protocol.if (url.pathname === "/control/state" && req.method === "GET") {- return this.json(res, 200, { connected: this.connected, servers: [...this.servers.values()].map(({ serverId, cloudId, enroll }) => ({ serverId, cloudId, host: enroll.host, connector: enroll.connector })),+ return this.json(res, 200, { connected: this.connected, servers: [...this.boxes.values()].map(({ boxId, teamId, state, count, revoked, enroll }) => ({ boxId, teamId, state, count, revoked, host: enroll.host, connector: enroll.connector })),heartbeats: this.heartbeats.length, lastHeartbeat: this.heartbeats.at(-1) ?? null, connections: this.connections.length });}+ if (url.pathname === "/control/accept" && req.method === "POST") {+ for (const box of this.boxes.values()) this.accept(box.boxId);+ return this.json(res, 200, { ok: true });+ }if (url.pathname === "/control/job" && req.method === "POST") {const { type, args, id } = JSON.parse((await this.body(req)).toString("utf8")) as { type: JobType; args: Record<string, unknown>; id?: string };try {diff --git a/connector/test/home-requests.test.ts b/connector/test/home-requests.test.tsnew file mode 100644index 0000000000..faf6aaf6b0--- /dev/null+++ b/connector/test/home-requests.test.ts@@ -0,0 +1,110 @@+import { readFileSync } from "node:fs";+import { createServer } from "node:http";+import { createConnection, type AddressInfo } from "node:net";+import type { Duplex } from "node:stream";++import { afterEach, describe, expect, it } from "vitest";++import type { AuditEvent } from "../src/audit.ts";+import { parseHead, RequestGate, serveRequest } from "../src/home-requests.ts";+import { MuxSession, type MuxStream } from "../src/mux.ts";++const cleanups: (() => Promise<void> | void)[] = [];+afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();+});++/** The Admin's side and the connector's, joined in memory: each frame one sends, the other receives. */+function joined(incoming: (stream: MuxStream, accept: () => void) => void) {+ const failures: string[] = [];+ let admin!: MuxSession;+ let box!: MuxSession;+ const to = (peer: () => MuxSession) => ({ send: (frame: Uint8Array) => queueMicrotask(() => peer().receive(frame)), bufferedAmount: 0, onceDrained: (listener: () => void) => queueMicrotask(listener) });+ admin = new MuxSession("phone", to(() => box), { failed: (reason) => failures.push(`admin: ${reason}`) });+ box = new MuxSession("computer", to(() => admin), { incoming, failed: (reason) => failures.push(`box: ${reason}`) });+ return { admin, box, failures };+}++const read = (stream: Duplex) => new Promise<string>((resolve) => {+ const chunks: Buffer[] = [];+ stream.on("data", (chunk: Buffer) => chunks.push(chunk));+ stream.on("end", () => resolve(Buffer.concat(chunks).toString("latin1")));+ stream.on("close", () => resolve(Buffer.concat(chunks).toString("latin1")));+});++async function home() {+ const requests: string[] = [];+ const server = createServer((req, res) => {+ requests.push(`${req.method} ${req.url}`);+ req.resume();+ req.on("end", () => res.writeHead(200, { "content-type": "text/plain", connection: "close" }).end("ok"));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ cleanups.push(() => new Promise<void>((resolve) => server.close(() => resolve())));+ const port = (server.address() as AddressInfo).port;+ const connectHome = () => new Promise<Duplex>((resolve, reject) => {+ const socket = createConnection({ host: "127.0.0.1", port });+ socket.once("connect", () => resolve(socket));+ socket.once("error", reject);+ });+ return { requests, connectHome };+}++describe("the Admin's requests to the home", () => {+ it("takes one HTTP/1.1 request a stream, with a plain body, and nothing that changes the protocol", () => {+ expect(parseHead("GET /api/cloud/health HTTP/1.1\r\nhost: a.example")).toEqual({ ok: true, head: { method: "GET", target: "/api/cloud/health", length: 0 } });+ expect(parseHead("POST /api/cloud/pairing HTTP/1.1\r\nContent-Length: 42")).toEqual({ ok: true, head: { method: "POST", target: "/api/cloud/pairing", length: 42 } });+ for (const head of [+ "CONNECT example.com:443 HTTP/1.1", "GET http://elsewhere.example/ HTTP/1.1", "GET / HTTP/1.0", "GET /\tx HTTP/1.1",+ "GET / HTTP/1.1\r\nUpgrade: websocket", "POST / HTTP/1.1\r\nTransfer-Encoding: chunked", "POST / HTTP/1.1\r\nContent-Length: -1", "GET / HTTP/1.1\r\nno colon",+ ]) expect(parseHead(head).ok, head).toBe(false);+ });++ it("passes the first request through and refuses a second one on the same stream", async () => {+ const heads: string[] = [];+ const bodies: (string | null)[] = [];+ const gate = new RequestGate((head) => heads.push(`${head.method} ${head.target}`), (body) => bodies.push(body));+ const out: Buffer[] = [];+ gate.on("data", (chunk: Buffer) => out.push(chunk));+ const failed = new Promise<Error>((resolve) => gate.on("error", resolve));+ gate.write("POST /api/cloud/pairing HTTP/1.1\r\ncontent-length: 2\r\n\r\n{}");+ gate.write("GET /api/bots HTTP/1.1\r\n\r\n");+ expect((await failed).message).toBe("a second request on one stream");+ expect(heads).toEqual(["POST /api/cloud/pairing"]);+ expect(bodies).toEqual(["{}"]);+ expect(Buffer.concat(out).toString()).toBe("POST /api/cloud/pairing HTTP/1.1\r\ncontent-length: 2\r\n\r\n{}");+ });++ it("over the channel: the home answers the first request, a pipelined second never reaches it, and both ends hold the profile", async () => {+ const { requests, connectHome } = await home();+ const audits: AuditEvent[] = [];+ const { admin, failures } = joined((stream, accept) => serveRequest(stream, accept, { connectHome, record: (event) => audits.push(event) }));+ const one = admin.openStream();+ const answer = read(one);+ one.write("GET /api/cloud/health?token=secret HTTP/1.1\r\nhost: home.example\r\n\r\nGET /api/bots HTTP/1.1\r\nhost: home.example\r\n\r\n");+ const text = await answer;+ expect(text).toBe("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n");+ expect(requests).toEqual([]);+ const two = admin.openStream();+ const second = read(two);+ two.end("GET /api/cloud/health?token=secret HTTP/1.1\r\nhost: home.example\r\n\r\n");+ expect(await second).toMatch(/^HTTP\/1\.1 200 OK\r\n[\s\S]*\r\n\r\n[\s\S]*ok/);+ expect(requests).toEqual(["GET /api/cloud/health?token=secret"]);+ expect(audits).toEqual([+ { event: "request", by: "admin", method: "GET", path: "/api/cloud/health", status: 400 },+ { event: "request", by: "admin", method: "GET", path: "/api/cloud/health", status: 200 },+ ]);+ expect(JSON.stringify(audits)).not.toContain("secret");+ expect(failures).toEqual([]);+ });++ it("refuses a stream the connector opened: only the Admin opens streams", () => {+ const { box } = joined(() => {});+ expect(() => box.openStream()).toThrow("yamux: computer_open");+ });++ it("is the phone relay's yamux profile, byte for byte", () => {+ const relay = readFileSync(new URL("../../companion/src/e2e/yamux.ts", import.meta.url), "utf8");+ expect(readFileSync(new URL("../src/yamux.ts", import.meta.url), "utf8")).toBe(relay);+ });+});diff --git a/connector/test/home.test.ts b/connector/test/home.test.tsindex cb55e0d802..5cc73d52cc 100644--- a/connector/test/home.test.ts+++ b/connector/test/home.test.ts@@ -237,7 +237,7 @@ describe("the home on an own server", () => {f.write("a.txt", "1");const { backup } = await f.home.backup("backup-1");f.docker.failCopy = true;- const admin = { origin: "https://cloud.example.test", token: "t".repeat(40) };+ const admin = { origin: "https://cloud.example.test", authorization: (jobId: string) => `Box token-for-${jobId}` };for (const job of [() => f.home.update("update-1", B), () => f.home.restore("restore-1", backup.id), () => f.home.importDisk("import-1", "https://storage.example.test/d.tgz", admin)]) {expect(await failure(job())).toMatchObject({ code: "docker", message: "Copying the data failed (cp: error writing '/to/big.bin': No space left on device); nothing was changed." });expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });@@ -289,13 +289,13 @@ describe("the home on an own server", () => {expect((await failure(f.home.restore("restore-2", "20260101-000000-0000"))).code).toBe("not_found");});- it("sends a gzip tar of /data to the Admin with the agent token, with the home running again meanwhile, and leaves no archive behind", async () => {+ it("sends a gzip tar of /data to the Admin with the box's token for that job, with the home running again meanwhile, and leaves no archive behind", async () => {const f = fixture();await started(f);f.write("a.txt", "1");- const result = await f.home.exportDisk("export-1", { origin: "https://cloud.example.test", token: "agent-token-0123456789abcdefghijklmnopqrst" });+ const result = await f.home.exportDisk("export-1", { origin: "https://cloud.example.test", authorization: (jobId) => `Box token-for-${jobId}` });expect(result).toEqual({ bytes: f.uploads[0].body.length, sha256: "0".repeat(64) });- expect(f.uploads).toEqual([{ url: "https://cloud.example.test/api/cloud/servers/agent/export/export-1", headers: { authorization: "Bearer agent-token-0123456789abcdefghijklmnopqrst" }, body: JSON.stringify([["a.txt", "1"]]) }]);+ expect(f.uploads).toEqual([{ url: "https://cloud.example.test/api/cloud/box/v1/export/export-1", headers: { authorization: "Box token-for-export-1" }, body: JSON.stringify([["a.txt", "1"]]) }]);expect(readdirSync(f.state.dir).filter((name) => name.startsWith("export-"))).toEqual([]);expect(f.docker.container("mausbot-home")?.status).toBe("running");});@@ -304,14 +304,14 @@ describe("the home on an own server", () => {const f = fixture();await started(f);f.write("old.txt", "1");- const admin = { origin: "https://cloud.example.test", token: "agent-token-0123456789abcdefghijklmnopqrst" };+ const admin = { origin: "https://cloud.example.test", authorization: (jobId: string) => `Box token-for-${jobId}` };const imported = await f.home.importDisk("import-1", "https://storage.example.test/disk.tgz?sig=x", admin);expect(imported).toMatchObject({ bytes: expect.any(Number), home: { state: "running" } });expect(f.data()).toEqual({ "imported.txt": "from the old home" });expect(f.docker.files("mausbot-snapshot")).toEqual({ "old.txt": "1" });expect(f.downloads[0]).toEqual({ url: "https://storage.example.test/disk.tgz?sig=x", headers: {} });- await f.home.importDisk("import-2", "https://cloud.example.test/api/cloud/servers/agent/import/import-2", admin);- expect(f.downloads[1].headers).toEqual({ authorization: `Bearer ${admin.token}` });+ await f.home.importDisk("import-2", "https://cloud.example.test/api/cloud/box/v1/import/import-2", admin);+ expect(f.downloads[1].headers).toEqual({ authorization: "Box token-for-import-2" });f.setArchive("not an archive");const bad = await failure(f.home.importDisk("import-3", "https://storage.example.test/bad.tgz", admin));expect(bad.toJobError()).toMatchObject({ code: "transfer_failed" });diff --git a/connector/test/install-script.test.ts b/connector/test/install-script.test.tsindex a19936cb2f..d737c2da99 100644--- a/connector/test/install-script.test.ts+++ b/connector/test/install-script.test.ts@@ -76,7 +76,7 @@ describe("install.sh", () => {expect(value("SECCOMP")).toBe(SECCOMP_FILE);expect(script).toContain('ADMIN_URL="${MAUSBOT_ADMIN_URL:-@MAUSBOT_ADMIN_URL@}"');expect(script).toContain('CONNECTOR_IMAGE="${MAUSBOT_CONNECTOR_IMAGE:-@MAUSBOT_CONNECTOR_IMAGE@}"');- expect(script).toContain('say "Connected. Your server shows up in MausBot in a minute."');+ expect(script).toContain(`say "Connected. Your server shows up in MausBot in a minute, for your team's Owner to accept."`);expect(script).toContain(`com.mausbot.instance=$instance`);expect(script).toContain("--restart unless-stopped --network host");expect(script).toContain("-v /var/run/docker.sock:/var/run/docker.sock -v \"$STATE_VOLUME:/state\" -v \"$ETC_DIR:/etc/mausbot:ro\" -v \"$AUDIT_DIR:/var/log/mausbot\"");diff --git a/connector/test/jobs.test.ts b/connector/test/jobs.test.tsindex 2f131d8dd6..721d5ba73a 100644--- a/connector/test/jobs.test.ts+++ b/connector/test/jobs.test.ts@@ -23,9 +23,9 @@ function runner(overrides: Partial<Record<keyof Home, unknown>> = {}) {const run = jobRunner({home,hostHealth: async () => ({ arch: "x86_64" }) as HostHealth,- identity: () => ({ version: "1.0.0", protocol: 1, image: null }),- admin: () => ({ origin: "https://cloud.example.test", token: "t" }),- selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: { version: "1.0.0", protocol: 1, image: job.args.image } } }),+ identity: () => ({ version: "1.0.0", protocol: 2, image: null }),+ admin: () => ({ origin: "https://cloud.example.test", authorization: (jobId) => `Box token-for-${jobId}` }),+ selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: { version: "1.0.0", protocol: 2, image: job.args.image } } }),});return { run, calls, pending };}@@ -34,7 +34,7 @@ describe("the jobs the connector runs", () => {it("answers status with a fresh health read, the copies and the connector, and host-health with the host", async () => {const { run, calls } = runner();expect(await run({ id: "s", type: "status", args: {} })).toEqual({- id: "s", ok: true, result: { home: { state: "running", image: HOME, health: null }, connector: { version: "1.0.0", protocol: 1, image: null }, backups: [], snapshot: null },+ id: "s", ok: true, result: { home: { state: "running", image: HOME, health: null }, connector: { version: "1.0.0", protocol: 2, image: null }, backups: [], snapshot: null },});expect(calls).toEqual(["refreshHealth"]);expect(await run({ id: "h", type: "host-health", args: {} })).toEqual({ id: "h", ok: true, result: { host: { arch: "x86_64" } } });diff --git a/connector/test/protocol.test.ts b/connector/test/protocol.test.tsindex 70dfc38c47..9e82d55e52 100644--- a/connector/test/protocol.test.ts+++ b/connector/test/protocol.test.ts@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";import { cloudRequestSignature as homeSignature } from "../../server/cloud-home.ts";import { cloudRequestSignature, summarizeHealth } from "../src/home-health.ts";-import { checkEnrollCode, checkEnrollResponse, checkHomeEnv, checkJob, checkTransferUrl, JOB_TYPES, REQUIRED_HOME_ENV } from "../src/protocol.ts";+import {+ checkConfig, checkEnrollCode, checkEnrollResponse, checkHello, checkHomeEnv, checkJob, checkJobPayload, checkTransferUrl, JOB_LIFETIME_MS, JOB_TYPES, REQUIRED_HOME_ENV,+} from "../src/protocol.ts";+import { generateKeyPair, seal, unseal } from "../src/signed.ts";const HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(64)}`;const CONNECTOR = `ghcr.io/milind-soni/mausbot-connector@sha256:${"b".repeat(64)}`;@@ -76,10 +79,12 @@ describe("the connector protocol", () => {});it("keeps an enrolment answer only when every field is the Admin's shape, and a code only as MausBot shows it", () => {- const good = { serverId: "srv_1a2b", cloudId: "cloud_3c4d", agentToken: "ombs_" + "t".repeat(43) };+ const key = generateKeyPair().publicKey;+ const good = { boxId: "box_1a2b3c4d5e6f", teamId: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", adminKeys: { k1: key }, state: "pending" };expect(checkEnrollResponse(good)).toEqual({ ok: true, value: good });expect(checkEnrollResponse({ ...good, extra: 1 })).toEqual({ ok: true, value: good });- for (const bad of [null, {}, { ...good, agentToken: "short" }, { ...good, serverId: "a/b" }, { ...good, cloudId: 3 }]) expect(checkEnrollResponse(bad).ok).toBe(false);+ for (const bad of [null, {}, { ...good, boxId: "a/b" }, { ...good, teamId: 3 }, { ...good, adminKeys: {} }, { ...good, adminKeys: { k1: key, k2: key, k3: key } },+ { ...good, adminKeys: { k1: "short" } }, { ...good, adminKeys: { "K 1": key } }, { ...good, state: "revoked" }]) expect(checkEnrollResponse(bad).ok, JSON.stringify(bad)).toBe(false);expect(checkEnrollCode("MB-1A2B-3C4D").ok).toBe(true);for (const code of ["", "abc", "MB 1A2B", "MB-1A2B;rm -rf /", "x".repeat(200)]) expect(checkEnrollCode(code).ok, code).toBe(false);});@@ -98,4 +103,47 @@ describe("the connector protocol", () => {expect(summarizeHealth(401, { error: "invalid_signature" }, HOME, 5)).toMatchObject({ ok: false, image: null, box: null });expect(summarizeHealth(0, null, HOME, 5).ok).toBe(false);});++ it("takes a hello only for this box, this connection's two nonces and this count", () => {+ const expected = { box: "box_1a2b3c4d5e6f", adminNonce: "a".repeat(43), boxNonce: "b".repeat(43), count: 7 };+ const hello = { t: "hello", kid: "k1", ...expected, now: 1_793_000_000_000, state: "accepted" };+ expect(checkHello(hello, expected).ok).toBe(true);+ for (const [field, value] of [["box", "box_other0000000"], ["adminNonce", "c".repeat(43)], ["boxNonce", "c".repeat(43)], ["count", 6], ["state", "revoked"], ["now", -1], ["t", "job"], ["keys", { k1: "x" }]] as const) {+ expect(checkHello({ ...hello, [field]: value }, expected).ok, field).toBe(false);+ }+ });++ it("takes a signed job only for this box and within its lifetime by the Admin's clock", () => {+ const iat = 1_793_000_000_000;+ const payload = { t: "job", kid: "k1", box: "box_1a2b3c4d5e6f", iat, exp: iat + JOB_LIFETIME_MS, job: { id: "j", type: "status" } };+ expect(checkJobPayload(payload, "box_1a2b3c4d5e6f", iat + 1000)).toEqual({ ok: true, job: { id: "j", type: "status" } });+ expect(checkJobPayload(payload, "box_other0000000", iat)).toMatchObject({ ok: false, code: "wrong_box" });+ expect(checkJobPayload(payload, "box_1a2b3c4d5e6f", iat + JOB_LIFETIME_MS + 1)).toMatchObject({ ok: false, code: "expired_job" });+ expect(checkJobPayload({ ...payload, exp: iat + JOB_LIFETIME_MS + 1 }, "box_1a2b3c4d5e6f", iat)).toMatchObject({ ok: false, code: "expired_job" });+ expect(checkJobPayload({ ...payload, t: "hello" }, "box_1a2b3c4d5e6f", iat)).toMatchObject({ ok: false, code: "unsigned_job" });+ });++ it("takes a config only for this box, with a window, ring, hold, image and offline hours in their shapes", () => {+ const config = { t: "config", kid: "k1", box: "box_1a2b3c4d5e6f", iat: 1, version: 2, state: "accepted",+ schedule: { window: { days: [0, 6], start: "22:00", end: "05:00", timeZone: "Europe/Berlin" }, ring: "late", holdUntil: null, image: HOME }, policy: { offlineHours: 72 } };+ expect(checkConfig(config, "box_1a2b3c4d5e6f").ok).toBe(true);+ expect(checkConfig(config, "box_other0000000").ok).toBe(false);+ for (const change of [{ version: 0 }, { schedule: { ...config.schedule, ring: "fast" } }, { schedule: { ...config.schedule, image: "ubuntu:latest" } },+ { schedule: { ...config.schedule, window: { ...config.schedule.window, start: "25:00" } } }, { schedule: { ...config.schedule, window: { ...config.schedule.window, days: [7] } } },+ { schedule: { ...config.schedule, window: { ...config.schedule.window, timeZone: "../../etc" } } }, { policy: { offlineHours: 10_000 } }]) {+ expect(checkConfig({ ...config, ...change }, "box_1a2b3c4d5e6f").ok, JSON.stringify(change)).toBe(false);+ }+ });++ it("opens an envelope only with the key its kid names, and only as it was signed", () => {+ const admin = generateKeyPair(), other = generateKeyPair();+ const envelope = seal({ t: "job", box: "b" }, "k1", admin.privateKey);+ expect(unseal(envelope, { k1: admin.publicKey })).toEqual({ ok: true, payload: { t: "job", box: "b", kid: "k1" } });+ expect(unseal(envelope, { k1: other.publicKey })).toEqual({ ok: false, why: "the signature does not verify" });+ expect(unseal(envelope, { k2: admin.publicKey })).toEqual({ ok: false, why: "signed by a key this side does not know" });+ const [body, signature] = envelope.split(".");+ const changed = Buffer.from(JSON.stringify({ t: "job", box: "c", kid: "k1" })).toString("base64url");+ expect(unseal(`${changed}.${signature}`, { k1: admin.publicKey }).ok).toBe(false);+ for (const bad of [`${body}`, `${body}.${signature}.x`, "", 7, `${"x".repeat(300_000)}.y`]) expect(unseal(bad, { k1: admin.publicKey }).ok).toBe(false);+ });});diff --git a/connector/test/self-update.test.ts b/connector/test/self-update.test.tsindex 54d15637e6..265d9ecfbf 100644--- a/connector/test/self-update.test.ts+++ b/connector/test/self-update.test.ts@@ -47,7 +47,7 @@ async function fixture() {const lines: string[] = [];const updater = (instance: string) => new SelfUpdater({docker, state, log: (line) => lines.push(line), instance, deadlineMs: 180_000, pollMs: 2_000,- identity: () => ({ version: "1.0.0", protocol: 1, image: instance === "instance-old" ? OLD : NEW }),+ identity: () => ({ version: "1.0.0", protocol: 2, image: instance === "instance-old" ? OLD : NEW }),now: () => clock,sleep: async (ms) => { clock += ms; },});@@ -66,7 +66,7 @@ describe("the connector replacing itself", () => {};const reply = await f.updater("instance-old").run(f.job, f.agent);expect(reply).toBeNull();- expect(candidateReply).toEqual({ id: "self-1", ok: true, result: { connector: { version: "1.0.0", protocol: 1, image: NEW } } });+ expect(candidateReply).toEqual({ id: "self-1", ok: true, result: { connector: { version: "1.0.0", protocol: 2, image: NEW } } });expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);const now = f.docker.container("mausbot-connector")!;expect(now.spec.Image).toBe(NEW);@@ -126,7 +126,7 @@ describe("the connector replacing itself", () => {const f = await fixture();const missing = `ghcr.io/milind-soni/mausbot-connector@sha256:${"3".repeat(64)}`;expect(await f.updater("instance-old").run({ ...f.job, args: { image: missing } }, f.agent)).toMatchObject({ ok: false, error: { code: "self_update_failed" } });- expect(await f.updater("instance-old").run({ ...f.job, args: { image: OLD } }, f.agent)).toEqual({ id: "self-1", ok: true, result: { connector: { version: "1.0.0", protocol: 1, image: OLD } } });+ expect(await f.updater("instance-old").run({ ...f.job, args: { image: OLD } }, f.agent)).toEqual({ id: "self-1", ok: true, result: { connector: { version: "1.0.0", protocol: 2, image: OLD } } });expect(f.agent).toMatchObject({ paused: 0, resumed: 0 });expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);expect(await f.updater("instance-unknown").run(f.job, f.agent)).toMatchObject({ ok: false, error: { code: "self_update_failed", message: expect.stringContaining("cannot find its own container") } });