Files
PaperClipAI/server/src/services/runtime-exposure/broker-client.ts
T
Dotta 4c349fe6b7 feat(runtime): managed Tailscale HTTPS lifecycle, durable runtime leases, and bounded control recovery (#11525)
<!-- Simplified Technical English (ASD-STE100). -->

> **Stacked pull request.** This targets #11524. Merge #11524 first.
Review only the second commit, `feat(runtime): managed Tailscale HTTPS
lifecycle...`.

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip starts and supervises managed runtime services, so an
agent's branch can be previewed while the agent works
> - The previous pull request added the host broker, the shared
contract, and the database columns, but no code used them
> - A managed runtime can only be exposed over HTTPS if it holds a
stable loopback port pair for the whole life of the service. The current
control path cannot promise this: two controls can race the same
execution workspace, a stranded control can stay `running` forever, and
a start can adopt a port it does not own
> - This pull request adds the HTTPS lifecycle and the control-path
hardening that the lifecycle depends on
> - The benefit is that a managed preview becomes reachable from another
device, and a managed control now always reaches a terminal state

## Linked Issues or Issue Description

No public GitHub issue exists. The change follows the feature request
template.

**Subsystem affected**

Managed workspace runtime services, workspace operations, the execution
workspace routes, and the workspace runtime UI.

**Problem or motivation**

A managed runtime service is reachable only on loopback, so a preview
cannot be opened from a phone or a second computer. Exposing it safely
needs an exclusively held port pair. Three existing gaps block that.
Overlapping controls can race the same workspace. A control whose owner
dies stays `running` and blocks the lane forever. Port allocation does
not confirm that the process holding a port is the process Paperclip
spawned.

**Proposed solution**

Add the exposure lifecycle on top of the broker from #11524: reserve
before spawn, expose after readiness, validate the public URL, and
remove on stop. In the same change, make managed controls mutually
exclusive per workspace, give each control a durable issue-owned lease
and a terminal state, and verify port ownership before use.

**Alternatives considered**

- Add HTTPS exposure without the control hardening. This was rejected
because a raced or stranded control makes exposure point at the wrong
process.
- Guard the lane with an in-memory lock only. This was rejected because
the lock does not survive a server restart, so the lane can be lost or
double-claimed.
- Trust the requested bind address. This was rejected because a checkout
that predates managed HTTPS overwrites `PAPERCLIP_BIND` from its own
`--bind` argument, and then binds the wildcard address.

**Roadmap alignment**

This completes the managed workspace runtime capability that already
exists. It adds no new product surface beyond the HTTPS link.

**Additional context**

This is the second of three pull requests. The third adds central
mediation of leased port pairs.

## What Changed

Exposure lifecycle:

- Add the server-side broker client and the exposure lifecycle manager.
The manager reserves the mapping before spawn, exposes after backend
readiness, validates the public URL, and removes the mapping on stop.
- Default managed worktree runtimes to `tailscale_https`, read exposure
intent from legacy `expose` blocks, and backfill runtimes that are still
HTTP-only.
- Verify listener ownership for the app port and its Vite HMR companion
before the broker is asked to expose anything. An unrelated listener on
either port fails the start closed.
- Force the loopback bind through argv instead of environment hints.
Leave a non-Paperclip service's `--bind` argument alone.
- Probe loopback for readiness instead of the public URL, and give Vite
HMR its own loopback-bound server in middleware mode.
- Preserve operator-declared Serve mappings across the managed
lifecycle, so cleanup never removes a mapping that Paperclip did not
create.
- Name which listener predicate denied an expose, so an operator can act
on the message.

Control-path hardening:

- Make `start`, `stop`, `restart`, and job `run` mutually exclusive per
execution workspace. An overlap gets `409
workspace_runtime_control_in_progress`, and authorization is still
checked first.
- Take a durable exclusivity lease on the execution workspace, owned by
the controlling issue. A different issue gets `409
workspace_runtime_lease_conflict` before any operation is recorded.
Board and operator actions bypass the lease.
- Give every control a terminal state. Each control stamps its owning
process and pid, heartbeats while it runs, and has a wall-clock ceiling.
Recovery of a stranded control uses a compare-and-swap on `updated_at`,
so a live owner is never stolen.
- Bound readiness probes, verify allocated port ownership on POSIX and
Windows, harden sibling port allocation, and reconcile desired runtimes
on server startup.
- Surface exposure state and bounded runtime errors in the workspace
runtime UI.
- Record the new behavior in `doc/DEVELOPING.md`.

## Verification

Focused checks, all run on this branch:

- `npx tsc --noEmit -p server/tsconfig.json` — 139 errors, exactly the
count on `master`. All 139 come from the unbuilt
`@paperclipai/plugin-sdk` package.
- `pnpm --filter @paperclipai/ui typecheck` — clean.
- Server suites, 177 tests pass across 9 files:
`workspace-runtime.test.ts`, `workspace-runtime-leases.test.ts`,
`workspace-runtime-control-recovery.test.ts`,
`execution-workspace-runtime-control-conflict.test.ts`,
`execution-workspace-runtime-lease-route.test.ts`,
`workspace-operations-reconciliation.test.ts`,
`workspace-runtime-start-terminality.test.ts`, `app-hmr-port.test.ts`,
and `workspace-runtime-ready-comment.test.ts`.
- Exposure unit suites, 77 tests pass: `src/services/runtime-exposure/`
and `workspace-runtime-exposure-backfill.test.ts`.
- UI: `WorkspaceRuntimeControls.test.tsx` and
`WorkspaceServiceControlBar.test.tsx` — 34 tests pass.

**One suite is red on the development host and is expected to be green
in CI.** `server/src/services/workspace-runtime-exposure.test.ts` has 10
failures on the machine used to write this branch. The cause is host
contamination, not the code. That machine already runs an HTTPS canary
that holds ports 42000, 42001, 52000, and 52001 on a tailnet address.
The suite allocates from the same range, so the new listener-ownership
check correctly reports:

```
listener_ownership_mismatch — port 42000 is bound to 100.123.243.20, 127.0.0.1,
fd7a:115c:a1e0:0:0:0:dd3a:f314 ... instead of loopback only
```

A CI runner has no listener on those ports, so the check sees loopback
only and the suite passes. Please confirm this from the CI result on
this pull request rather than from a local run on a host that already
exposes a managed runtime. This is a real weakness of the current test
fixture, and the third pull request in the series removes it by
allocating the pair through a central mediator instead of a stubbed
availability check.

`workspace-runtime-https-live-exercise.test.ts` needs a live `tailscale`
host and was not run locally.

## Risks

- This is the behavior-bearing pull request of the three, so it carries
the most risk.
- Two new `409` responses appear on managed control routes. A caller
that assumed a control always starts must handle a conflict. Board and
operator actions are deliberately exempt, so an agent lease cannot lock
an operator out.
- Managed worktree runtimes now default to `tailscale_https`. If the
host has no working broker, the start fails closed and reports the
exposure failure instead of silently serving plain HTTP. This is
intended, and it is the reason the failure message names the denying
predicate.
- Startup reconciliation touches persisted runtime rows. It is scoped to
desired state and does not resurrect a service that never came up.
- The lease has a 30-minute time to live and explicit release paths, so
a crashed owner cannot hold a lane forever.
- No migration runs in this pull request. The tables and columns land in
#11524.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR.

## Model Used

Claude Opus 5 (`claude-opus-5`), 1M context window, extended thinking,
with tool use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass, with the one
host-contaminated suite explained above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-08-17 06:23:33 -04:00

293 lines
10 KiB
TypeScript

/**
* Server-side client for the least-privilege Tailscale HTTPS host broker.
*
* The Paperclip server process holds NO Tailscale operator authority. Its only
* way to publish a same-number HTTPS-to-loopback listener is to ask the broker
* over its Unix domain socket. This client speaks the exact versioned,
* length-prefixed, byte-bounded wire protocol implemented by the broker's
* socket server (PAP-17049 plan, PAP-17050 verdict requirement #5).
*
* Framing (must match `packages/tailscale-https-broker/src/socket-server.ts`):
* [4-byte big-endian body length][utf-8 JSON body]
* One request per connection; the broker writes a single framed response and
* closes the socket.
*
* Everything the broker returns is untrusted: the client validates the response
* shape before handing it back and never logs lease handles.
*/
import net from "node:net";
/**
* Must match the broker's `BROKER_PROTOCOL_VERSION`. Kept as a local constant
* (rather than a dependency on the host-side broker package, which is installed
* and versioned separately under its own operator account) so the server does
* not import host-privileged code just to speak the wire protocol.
*/
const BROKER_PROTOCOL_VERSION = 1;
/** Must match the broker's `MAX_REQUEST_BYTES` (8 KiB). */
const MAX_REQUEST_BYTES = 8 * 1024;
/** Must match the broker's `MAX_RESPONSE_BYTES` (16 KiB). */
const MAX_RESPONSE_BYTES = 16 * 1024;
const LENGTH_PREFIX_BYTES = 4;
/** Listener purposes the broker understands. */
export type BrokerListenerPurpose = "app" | "vite_hmr";
export interface BrokerListenerRequest {
purpose: BrokerListenerPurpose;
/** Public HTTPS port == loopback target port (same-number invariant). */
port: number;
}
export interface BrokerExposeResult {
handle: string;
publicPorts: number[];
}
export interface BrokerReserveResult {
handle: string;
reservedPorts: number[];
}
export interface BrokerRemoveResult {
removedPorts: number[];
}
export interface BrokerOwnedListener {
runtimeId: string;
port: number;
purpose: BrokerListenerPurpose;
}
/**
* Error surfaced to the exposure manager. `code` is the broker's stable machine
* code (or a transport-level code) so lifecycle logic can branch without
* string-matching human messages.
*/
export class BrokerClientError extends Error {
constructor(
readonly code: string,
message: string,
) {
super(message);
this.name = "BrokerClientError";
}
}
/**
* Minimal broker capability surface the exposure manager depends on. Defining
* it as an interface lets tests inject a fake broker with zero sockets.
*/
export interface BrokerClient {
reserve(runtimeId: string, listeners: BrokerListenerRequest[]): Promise<BrokerReserveResult>;
expose(runtimeId: string, handle: string): Promise<BrokerExposeResult>;
remove(runtimeId: string, handle: string): Promise<BrokerRemoveResult>;
list(): Promise<BrokerOwnedListener[]>;
}
export interface UnixBrokerClientOptions {
socketPath: string;
/** Per-request connect+round-trip deadline. Defaults to 5s. */
timeoutMs?: number;
/**
* Seam for tests: open a duplex stream to the broker. Defaults to a real Unix
* socket connection. Any injected connector must behave like a `net.Socket`.
*/
connect?: (socketPath: string) => net.Socket;
}
let requestCounter = 0;
function nextRequestId(): string {
requestCounter = (requestCounter + 1) % 1_000_000;
// Matches the broker's REQUEST_ID_RE (`[A-Za-z0-9_-]{1,64}`). No time/random
// needed for correctness; the broker keys responses by requestId echo only.
return `req-${requestCounter.toString(36)}`;
}
/**
* Unix-domain-socket implementation of {@link BrokerClient}. Each call opens a
* fresh connection, sends one length-prefixed frame, reads one length-prefixed
* response frame, and closes.
*/
export class UnixBrokerClient implements BrokerClient {
private readonly socketPath: string;
private readonly timeoutMs: number;
private readonly connect: (socketPath: string) => net.Socket;
constructor(options: UnixBrokerClientOptions) {
this.socketPath = options.socketPath;
this.timeoutMs = options.timeoutMs ?? 5_000;
this.connect = options.connect ?? ((p) => net.createConnection(p));
}
async reserve(
runtimeId: string,
listeners: BrokerListenerRequest[],
): Promise<BrokerReserveResult> {
const response = await this.roundTrip({
v: BROKER_PROTOCOL_VERSION,
op: "reserve",
requestId: nextRequestId(),
runtimeId,
listeners: listeners.map((l) => ({ purpose: l.purpose, port: l.port })),
});
if (
typeof response.handle !== "string" ||
!Array.isArray(response.reservedPorts) ||
!response.reservedPorts.every((p) => Number.isInteger(p))
) {
throw new BrokerClientError("malformed_response", "reserve response missing handle/reservedPorts");
}
return { handle: response.handle, reservedPorts: response.reservedPorts as number[] };
}
async expose(runtimeId: string, handle: string): Promise<BrokerExposeResult> {
const response = await this.roundTrip({
v: BROKER_PROTOCOL_VERSION,
op: "expose",
requestId: nextRequestId(),
runtimeId,
handle,
});
if (
typeof response.handle !== "string" ||
!Array.isArray(response.publicPorts) ||
!response.publicPorts.every((p) => Number.isInteger(p))
) {
throw new BrokerClientError("malformed_response", "expose response missing handle/publicPorts");
}
return { handle: response.handle, publicPorts: response.publicPorts as number[] };
}
async remove(runtimeId: string, handle: string): Promise<BrokerRemoveResult> {
const response = await this.roundTrip({
v: BROKER_PROTOCOL_VERSION,
op: "remove",
requestId: nextRequestId(),
runtimeId,
handle,
});
if (!Array.isArray(response.removedPorts) || !response.removedPorts.every((p) => Number.isInteger(p))) {
throw new BrokerClientError("malformed_response", "remove response missing removedPorts");
}
return { removedPorts: response.removedPorts as number[] };
}
async list(): Promise<BrokerOwnedListener[]> {
const response = await this.roundTrip({
v: BROKER_PROTOCOL_VERSION,
op: "list",
requestId: nextRequestId(),
});
if (!Array.isArray(response.listeners)) {
throw new BrokerClientError("malformed_response", "list response missing listeners");
}
return response.listeners.map((entry): BrokerOwnedListener => {
const listener = entry as Record<string, unknown>;
if (
typeof listener.runtimeId !== "string" ||
!Number.isInteger(listener.port) ||
(listener.purpose !== "app" && listener.purpose !== "vite_hmr")
) {
throw new BrokerClientError("malformed_response", "list returned a malformed listener");
}
return {
runtimeId: listener.runtimeId,
port: listener.port as number,
purpose: listener.purpose,
};
});
}
/** Send one request frame, resolve the single framed response as an object. */
private roundTrip(request: unknown): Promise<Record<string, unknown>> {
const body = Buffer.from(JSON.stringify(request), "utf8");
if (body.byteLength > MAX_REQUEST_BYTES) {
return Promise.reject(new BrokerClientError("request_too_large", "broker request exceeds size limit"));
}
const frame = Buffer.allocUnsafe(LENGTH_PREFIX_BYTES + body.byteLength);
frame.writeUInt32BE(body.byteLength, 0);
body.copy(frame, LENGTH_PREFIX_BYTES);
return new Promise((resolve, reject) => {
const socket = this.connect(this.socketPath);
const chunks: Buffer[] = [];
let received = 0;
let expected = -1;
let settled = false;
const done = (fn: () => void): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
socket.removeAllListeners();
socket.destroy();
fn();
};
const timer = setTimeout(() => {
done(() => reject(new BrokerClientError("cli_timeout", "broker request timed out")));
}, this.timeoutMs);
timer.unref?.();
socket.on("error", (err: Error) => {
done(() => reject(new BrokerClientError("transport_error", err.message)));
});
socket.on("close", () => {
// Closed before a full response was parsed.
done(() => reject(new BrokerClientError("transport_error", "broker closed connection early")));
});
socket.on("data", (chunk: Buffer) => {
received += chunk.byteLength;
if (received > LENGTH_PREFIX_BYTES + MAX_RESPONSE_BYTES) {
done(() => reject(new BrokerClientError("malformed_response", "broker response exceeds size limit")));
return;
}
chunks.push(chunk);
const buf = Buffer.concat(chunks);
if (expected < 0) {
if (buf.byteLength < LENGTH_PREFIX_BYTES) return;
expected = buf.readUInt32BE(0);
if (expected > MAX_RESPONSE_BYTES) {
done(() => reject(new BrokerClientError("malformed_response", "broker response length invalid")));
return;
}
}
if (buf.byteLength < LENGTH_PREFIX_BYTES + expected) return;
const payload = buf.subarray(LENGTH_PREFIX_BYTES, LENGTH_PREFIX_BYTES + expected).toString("utf8");
let parsed: unknown;
try {
parsed = JSON.parse(payload);
} catch {
done(() => reject(new BrokerClientError("malformed_response", "broker response is not valid JSON")));
return;
}
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
done(() => reject(new BrokerClientError("malformed_response", "broker response is not an object")));
return;
}
const obj = parsed as Record<string, unknown>;
if (obj.ok === false) {
const code = typeof obj.code === "string" ? obj.code : "internal_error";
const message = typeof obj.message === "string" ? obj.message : code;
done(() => reject(new BrokerClientError(code, message)));
return;
}
if (obj.ok !== true) {
done(() => reject(new BrokerClientError("malformed_response", "broker response missing ok flag")));
return;
}
done(() => resolve(obj));
});
socket.on("connect", () => {
socket.write(frame);
});
});
}
}