Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ To update, run `vmbridge update`. It downloads the latest release for this machi
the release's `SHA256SUMS` (and its build attestation too, when the GitHub CLI is installed and signed
in), replaces the installed file and restarts the background service, and devices reconnect on their
own. `vmbridge update --check` only says whether there is a newer release. The dashboard shows when
one is out. Running the install command again also updates.
one is out. When VM Bridge runs as the background service, its **Update** button does the same as
`vmbridge update` and reloads the page on the new version. Running the install command again also
updates.

Or run it on Cloudflare, with no machine of your own: see [Cloudflare Workers](#cloudflare-workers).

Expand Down Expand Up @@ -246,6 +248,10 @@ you add to it) is the only one. To change the password, change the secret under
There is no machine to read skills or `AGENTS.md` from, so upload skills and paste instructions under
**Skills**. How it works, limits and costs: [docs/cloudflare.md](docs/cloudflare.md).

The Worker deploys from your copy on GitHub, so it updates when that copy gets a new release. The
dashboard shows when one is out, with the commands under **How to update**. See
[Updating](docs/cloudflare.md#updating).

## Commands

```
Expand Down
9 changes: 6 additions & 3 deletions apps/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { parseArgs } from "node:util";
import { dashboardKey, dataDir, defaultPort, start, version } from "@vmbridge/server";
import { compiled, dashboardKey, dataDir, defaultPort, start, version } from "@vmbridge/server";
import { pidFile, restartSignal, runningPid, stopProcess } from "./process.ts";
import { logPath, protectLog, service, serviceAddresses } from "./service.ts";
import { update } from "./update.ts";
import { update, updateFromDashboard } from "./update.ts";

const help = `VM Bridge ${version}

Expand Down Expand Up @@ -116,7 +116,10 @@ async function run(options: { host?: string; port: number }) {
await stopProcess(existing, restartSignal, restartDeadlineMs + 5_000);
}
await ensureKey({ ask: false });
const server = await start(options);
// The dashboard installs updates only for the background service, which the update starts again. A terminal's VM
// Bridge would end with nothing to start it, so its dashboard shows `vmbridge update` instead.
const asService = compiled && (await service.pid()) === process.pid;
const server = await start({ ...options, ...(asService ? { installUpdate: updateFromDashboard } : {}) });
mkdirSync(dataDir(), { recursive: true, mode: 0o700 });
writeFileSync(pidFile(), String(process.pid));
// A service installed by an older version left its log readable by everyone.
Expand Down
35 changes: 34 additions & 1 deletion apps/cli/src/service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { spawn } from "node:child_process";
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { childEnv, compiled, dataDir } from "@vmbridge/server";
Expand Down Expand Up @@ -44,6 +45,9 @@ function environment() {
};
}

/** What a command run outside the service needs: VM Bridge's own update finds the data directory with it. */
const detachedEnv = () => childEnv(process.env.VMBRIDGE_HOME ? { VMBRIDGE_HOME: process.env.VMBRIDGE_HOME } : {});

async function exec(args: string[]) {
const child = Bun.spawn(args, { stdout: "pipe", stderr: "pipe", stdin: "ignore", env: childEnv() });
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
Expand Down Expand Up @@ -129,6 +133,20 @@ ${env}
await must(["launchctl", "kickstart", `${this.domain()}/${label}`]);
},

/**
* Runs `args` with its output appended to `log`, and resolves with its exit code. It runs in its own process group,
* which launchd leaves running when the service exits, so it can stop and start the service.
*/
detached(args: string[], log: string) {
const out = openSync(log, "a", 0o600);
const child = spawn(args[0]!, args.slice(1), { detached: true, stdio: ["ignore", out, out], env: detachedEnv() });
closeSync(out);
return new Promise<number>((resolve) => {
child.on("error", () => resolve(1));
child.on("exit", (code) => resolve(code ?? 1));
});
},

async uninstall() {
await this.stop();
rmSync(this.plist(), { force: true });
Expand Down Expand Up @@ -186,6 +204,20 @@ WantedBy=default.target
await must(["systemctl", "--user", "start", "vmbridge.service"]);
},

/**
* Runs `args` with its output appended to `log`, and resolves with its exit code. It runs as its own transient unit:
* systemd stops everything in the service's unit when it exits, which would end a plain child halfway.
*/
async detached(args: string[], log: string) {
const env = Object.entries(detachedEnv()).map(([key, value]) => `--setenv=${key}=${value}`);
const output = [`--property=StandardOutput=append:${log}`, `--property=StandardError=append:${log}`];
const child = Bun.spawn(["systemd-run", "--user", "--collect", "--quiet", "--wait", ...output, ...env, "--", ...args], {
stdio: ["ignore", "ignore", "ignore"],
env: childEnv(),
});
return await child.exited;
},

async uninstall() {
if (!existsSync(this.unit())) return;
await exec(["systemctl", "--user", "disable", "--now", "vmbridge.service"]);
Expand All @@ -201,6 +233,7 @@ const unsupported = {
stop: async () => false,
pid: async (): Promise<number | null> => null,
start: async () => {},
detached: async (_: string[], __: string) => 1,
uninstall: async () => {},
};

Expand Down
17 changes: 15 additions & 2 deletions apps/cli/src/update.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { checksumFor, childEnv, compiled, isNewer, latestVersion, releaseRepo, version } from "@vmbridge/server";
import { checksumFor, childEnv, compiled, dataDir, isNewer, latestVersion, releaseRepo, version } from "@vmbridge/server";
import { pidFile, restartSignal, runningPid, stopProcess } from "./process.ts";
import { service } from "./service.ts";

Expand Down Expand Up @@ -94,3 +94,16 @@ export async function update({ check }: { check: boolean }) {
console.log(`Updated VM Bridge from ${version} to ${latest}.`);
await restart(latest);
}

/**
* The dashboard's Update button, in the background service: runs `vmbridge update` outside the service, since the
* update stops the service and starts it again on the new release. Rejects with the update's last line when it fails;
* when it works, this process is stopped first.
*/
export async function updateFromDashboard() {
const log = join(dataDir(), "update.log");
writeFileSync(log, "", { mode: 0o600 });
const code = await service.detached([process.execPath, "update"], log);
const last = readFileSync(log, "utf8").trim().split("\n").at(-1);
throw new Error(last || (code === 0 ? "The update finished, but VM Bridge did not restart." : "The update failed."));
}
36 changes: 33 additions & 3 deletions apps/server/src/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
type RepoRule,
type VmInfo,
type VmSize,
type BridgeUpdate,
} from "@vmbridge/contracts";
import { analyticsReport } from "./analytics.ts";
import { InvalidSignIn, type AgentAuth, type TokenInput } from "./agent-auth/profiles.ts";
Expand Down Expand Up @@ -62,8 +63,8 @@ export interface AdminDeps {
network: BridgeNetwork;
/** Where the dashboard password is set instead of the dashboard, such as a Worker's secret. Null when it can be changed here. */
passwordSource: string | null;
/** A newer VM Bridge release that `vmbridge update` installs, or null. */
availableUpdate: () => string | null;
/** A newer VM Bridge release, or null, how this runtime moves to it, and the install the Update button runs, if it has one. */
update: { available: () => string | null; how: BridgeUpdate["how"]; install: (() => Promise<void>) | null };
settings: Settings;
secrets: Secrets;
store: Store;
Expand Down Expand Up @@ -126,6 +127,10 @@ function timeRange(request: Request) {
* Secret values go in and never come out: responses only say whether each one is set.
*/
export class Admin {
/** The dashboard's install of a new release is running. A second Update click while it runs does nothing. */
private installing = false;
private installError: string | null = null;

constructor(private readonly deps: AdminDeps) {}

async fetch(request: Request, origin: RequestOrigin): Promise<Response> {
Expand Down Expand Up @@ -195,6 +200,25 @@ export class Admin {
return json({ ok: true });
}
if (path === "/overview" && method === "GET") return json(this.overview());
if (path === "/update" && method === "POST") {
const { install, available } = this.deps.update;
if (!install || !available()) throw new BadRequest("There is no update to install from the dashboard.");
if (!this.installing) {
this.installing = true;
this.installError = null;
// When the install works, VM Bridge restarts on the new release before this settles.
void install()
.catch((error) => {
this.installError = message(error);
})
.finally(() => {
this.installing = false;
fleet.emit("changed");
});
fleet.emit("changed");
}
return json({ ok: true }, 202);
}
if (path === "/events" && method === "GET") return this.events(request);
if (path === "/traffic" && method === "GET") return json(this.deps.traffic.recent);
if (path === "/usage" && method === "GET") {
Expand Down Expand Up @@ -628,6 +652,12 @@ export class Admin {
this.deps.hub.emit("config");
}

private availableUpdate(): BridgeUpdate | null {
const version = this.deps.update.available();
if (!version) return null;
return { version, how: this.deps.update.how, installing: this.installing, error: this.installError };
}

overview(): Overview {
const { settings, secrets, store, fleet, hub, clients, gateway } = this.deps;
const defaultProvider = settings.get("defaultProvider");
Expand Down Expand Up @@ -680,7 +710,7 @@ export class Admin {
};
});
return {
bridge: { id: settings.get("bridgeId"), version: this.deps.version, startedAt: this.deps.startedAt, update: this.deps.availableUpdate() },
bridge: { id: settings.get("bridgeId"), version: this.deps.version, startedAt: this.deps.startedAt, update: this.availableUpdate() },
setup: {
provider: Boolean(defaultProvider),
github: secrets.has("github.token"),
Expand Down
34 changes: 15 additions & 19 deletions apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { networkInfo, wantedHosts } from "./bun/network.ts";
import { Secrets, type Plaintext } from "./settings.ts";
import type { Sql } from "./sql.ts";
import { CloudflareTunnel, requestOrigin } from "./bun/tunnel.ts";
import { isNewer, latestVersion, releaseCheckMs } from "./release.ts";
import { releaseCheck } from "./release.ts";
import { isWatchPath, type Viewer } from "./watch/watch.ts";

/** A T3 client's RPC socket, or a relayed stream's: a watch page's or a preview tab's. */
Expand Down Expand Up @@ -80,6 +80,11 @@ export interface StartOptions {
/** Listen on this one address instead of loopback, Tailscale and the local network switch. 0.0.0.0 is every network. */
host?: string;
port?: number;
/**
* Installs the latest release and restarts VM Bridge on it, for the dashboard's Update button. It rejects when the
* install fails; when it works, this process is stopped before it settles. Without it the dashboard shows the command.
*/
installUpdate?: () => Promise<void>;
}

export async function start(options: StartOptions = {}) {
Expand Down Expand Up @@ -111,11 +116,14 @@ export async function start(options: StartOptions = {}) {
let listeners: Listeners<Socket>;
const served = () => ({ hosts: listeners.hosts(), port: listeners.port, fixed: host !== undefined, localNetwork: settings.get("localNetwork") });
network = new BunNetwork({ served, applyAddresses: () => listeners.apply(), settings, secrets, tunnel: () => tunnel });
const availableUpdate = () => {
const latest = settings.get("latestRelease")?.version;
return latest && isNewer(latest, version) ? latest : null;
// Only the release binary checks (below): from source, `git pull` updates.
const release = releaseCheck(settings, version);
const update = {
available: release.available,
how: options.installUpdate ? ("dashboard" as const) : ("command" as const),
install: options.installUpdate ?? null,
};
const admin = new Admin({ ...bridge, version, startedAt: Date.now(), network, passwordSource: null, availableUpdate });
const admin = new Admin({ ...bridge, version, startedAt: Date.now(), network, passwordSource: null, update });
// A relayed stream's socket carries its viewer; any other is a T3 client's RPC socket, so the casts only drop the viewer case.
const websocket: WebSocketHandler<Socket> = {
maxPayloadLength: 16 * 1024 * 1024,
Expand Down Expand Up @@ -209,24 +217,12 @@ export async function start(options: StartOptions = {}) {
};
// Follows Tailscale coming up or changing address, and the local network appearing or changing.
const addresses = { name: "addresses", everyMs: 5_000, run: () => listeners.apply() };
// The dashboard's update notice. Only the release binary checks: from source, `git pull` updates.
const releaseCheck = {
name: "release check",
everyMs: 60 * 60_000,
run: async () => {
const saved = settings.get("latestRelease");
if (saved && Date.now() - saved.checkedAt < releaseCheckMs) return;
// Offline or limited by GitHub: the next hourly run tries again.
const latest = await latestVersion().catch(() => null);
if (latest) settings.set("latestRelease", { version: latest, checkedAt: Date.now() });
},
};
if (compiled) void releaseCheck.run();
if (compiled) void release.job.run();
const stopJobs = runJobs([
...bridgeJobs({ hub, fleet, stats, usage, budget, traffic, watch }),
localSkills,
...(host ? [] : [addresses]),
...(compiled ? [releaseCheck] : []),
...(compiled ? [release.job] : []),
]);
void fleet.resume();
// Accounts saved by older versions lack the details the dashboard shows.
Expand Down
26 changes: 26 additions & 0 deletions apps/server/src/release.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// VM Bridge's own releases on GitHub: the dashboard's update notice and `vmbridge update` both read them.

import type { Job } from "./jobs.ts";
import type { Settings } from "./settings.ts";

export const releaseRepo = "vkpdeveloper/vmbridge";

/** Checked at most this often for the dashboard, since GitHub limits requests without a token to 60 an hour. */
Expand Down Expand Up @@ -43,3 +46,26 @@ export function checksumFor(sums: string, file: string): string | null {
}
return null;
}

/**
* The dashboard's update notice: a job that asks GitHub for the latest release at most every releaseCheckMs and saves
* the answer, and the newer release it found, if any.
*/
export function releaseCheck(settings: Settings, current: string, fetcher: Fetcher = fetch) {
const job: Job = {
name: "release check",
everyMs: 60 * 60_000,
run: async () => {
const saved = settings.get("latestRelease");
if (saved && Date.now() - saved.checkedAt < releaseCheckMs) return;
// Offline or limited by GitHub: the next hourly run tries again.
const latest = await latestVersion(fetcher).catch(() => null);
if (latest) settings.set("latestRelease", { version: latest, checkedAt: Date.now() });
},
};
const available = () => {
const latest = settings.get("latestRelease")?.version;
return latest && isNewer(latest, current) ? latest : null;
};
return { job, available };
}
8 changes: 6 additions & 2 deletions apps/server/src/workers/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { keyFromText, keyVariable } from "../encryption.ts";
import { message } from "../fleet.ts";
import type { Upgrade } from "../gateway/http.ts";
import { bridgeJobs } from "../jobs.ts";
import { releaseCheck } from "../release.ts";
import { isWatchPath, type WatchUpgrade } from "../watch/watch.ts";
import { workersFetchCompat } from "../providers/workers-fetch.ts";
import { withSecurityHeaders } from "../security-headers.ts";
Expand Down Expand Up @@ -95,8 +96,11 @@ export class BridgeObject extends DurableObject<Env> {
secrets.set(passwordSourceSecret, source);
}

const admin = new Admin({ ...bridge, version: packageJson.version, startedAt: Date.now(), network: workerNetwork, passwordSource: `the Worker's ${passwordVariable} secret`, availableUpdate: () => null });
const jobs = new AlarmJobs(this.ctx.storage, bridgeJobs({ hub, fleet, stats, usage, budget, traffic, watch }));
// A Worker updates when its GitHub repository gets the new release, so the dashboard shows how instead of a button.
const release = releaseCheck(bridge.settings, packageJson.version);
const update = { available: release.available, how: "cloudflare" as const, install: null };
const admin = new Admin({ ...bridge, version: packageJson.version, startedAt: Date.now(), network: workerNetwork, passwordSource: `the Worker's ${passwordVariable} secret`, update });
const jobs = new AlarmJobs(this.ctx.storage, [...bridgeJobs({ hub, fleet, stats, usage, budget, traffic, watch }), release.job]);
// A recreated Durable Object already knows its address; without this, links would read as off until the next alarm.
await watch.refresh();
void fleet.resume();
Expand Down
Loading