feat(daemon): HTTP/WS/SSE surface with auth, static, command routing and event relay

- Hono app + ws upgrade server, ephemeral-port friendly, idempotent close
- device tokens (sha256 + timingSafeEqual), one-time pairing, Origin allowlist
- SPA static serving with traversal protection and cache policy
- command router with 5-min clientRequestId dedupe and protocol error mapping
- 66 tests against fake InstanceManager/WorkspaceStore/Bus
This commit is contained in:
yuez committed 2026-10-21 11:14:12 +08:00
1 parent bdcab3ce29
commit ba3719fad9
21 files changed
+3619

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
/**
* Daemon configuration.
*
* Defaults follow `docs/protocol.md`; deployment-specific values come from the
* environment so `pi2d` can be started without a config file.
*/
import { fileURLToPath } from "node:url";
import { daemonTokenPath, dataDir } from "./core/paths.js";
export const DEFAULT_PORT = 7676;
export const DEFAULT_MAX_BODY_BYTES = 8 * 1024 * 1024;
export const DEFAULT_MAX_FRAME_BYTES = 8 * 1024 * 1024;
export const DEFAULT_MAX_CONNECTIONS = 64;
export interface Limits {
maxBodyBytes: number;
maxFrameBytes: number;
maxConnections: number;
}
export interface Config {
host: string;
/** TCP port; `0` asks the OS for an ephemeral port (tests). */
port: number;
/** Built web UI (`<repo>/web/dist` by default). */
staticDir: string;
corsOrigins: string[];
limits: Limits;
tokenPath: string;
deviceStorePath: string;
}
export type ConfigEnv = Record<string, string | undefined>;
function defaultStaticDir(): string {
return fileURLToPath(new URL("../web/dist", import.meta.url));
}
function parsePort(raw: string | undefined): number {
if (raw === undefined || raw.trim() === "") return DEFAULT_PORT;
if (!/^\d+$/.test(raw.trim())) throw new Error(`PI2_PORT must be an integer, got "${raw}"`);
const port = Number(raw);
if (!Number.isSafeInteger(port) || port < 0 || port > 65535) {
throw new Error(`PI2_PORT must be between 0 and 65535, got "${raw}"`);
}
return port;
}
function parseOrigins(raw: string | undefined, port: number): string[] {
if (raw !== undefined) {
return raw
.split(",")
.map((origin) => origin.trim())
.filter((origin) => origin.length > 0);
}
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`];
}
export function loadConfig(env: ConfigEnv = process.env): Config {
const port = parsePort(env.PI2_PORT);
const host = env.PI2_HOST?.trim() || "127.0.0.1";
return {
host,
port,
staticDir: env.PI2_STATIC_DIR?.trim() || defaultStaticDir(),
corsOrigins: parseOrigins(env.PI2_ORIGINS, port),
limits: {
maxBodyBytes: DEFAULT_MAX_BODY_BYTES,
maxFrameBytes: DEFAULT_MAX_FRAME_BYTES,
maxConnections: DEFAULT_MAX_CONNECTIONS,
},
tokenPath: daemonTokenPath(),
deviceStorePath: `${dataDir()}/devices.json`,
};
}
+293
View File
@@ -0,0 +1,293 @@
/**
* Device token store (daemon-owned) and pairing helpers.
*
* Tokens are bearer credentials for the HTTP/WS surfaces. Only a SHA-256 hash
* is persisted, in `$PI2_DATA_DIR/devices.json` (mode 0600, atomic replace).
*/
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { dataDir } from "../core/paths.js";
import { ERROR_CODES } from "../protocol/errors.js";
import { DaemonError } from "./errors.js";
export type DeviceKind = "phone" | "laptop" | "tablet";
export type Scope = "read" | "steer" | "control" | "admin";
export const DEVICE_KINDS: readonly DeviceKind[] = ["phone", "laptop", "tablet"];
export const SCOPES: readonly Scope[] = ["read", "steer", "control", "admin"];
export const DEFAULT_SCOPES: readonly Scope[] = ["read", "steer", "control"];
export interface DeviceRecord {
id: string;
name: string;
kind: DeviceKind;
scopes: Scope[];
tokenHash: string;
createdAt: number;
lastSeenAt: number;
revokedAt: number | null;
}
export type DevicePublic = Omit<DeviceRecord, "tokenHash">;
export interface CreateDeviceInput {
name: string;
kind: DeviceKind;
scopes?: Scope[];
}
export interface PairCode {
code: string;
url: string;
expiresAt: number;
nonce: string;
}
export interface RedeemPairInput {
code: string;
deviceName: string;
kind: DeviceKind;
}
export interface RedeemPairResult {
token: string;
device: DevicePublic;
}
export interface AuthStoreOptions {
/** Defaults to `<dataDir>/devices.json`. */
path?: string;
now?: () => number;
baseUrl?: string;
/** `touchDevice` write throttle. */
touchIntervalMs?: number;
}
interface PairEntry {
code: string;
nonce: string;
expiresAt: number;
used: boolean;
}
interface PersistedDevices {
version: 1;
devices: DeviceRecord[];
}
export function hashToken(rawToken: string): string {
return createHash("sha256").update(rawToken, "utf8").digest("hex");
}
/** Constant-time comparison of two hex digests (length is not secret here). */
export function timingSafeEqualHex(left: string, right: string): boolean {
if (left.length !== right.length) return false;
try {
return timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
} catch {
return false;
}
}
/** Non-browser requests (no Origin) are allowed; unknown origins are not. */
export function isAllowedOrigin(origin: string | undefined, allowList: readonly string[]): boolean {
if (origin === undefined || origin === "") return true;
const normalized = origin.replace(/\/+$/, "");
return allowList.some((allowed) => allowed.replace(/\/+$/, "") === normalized);
}
function isDeviceKind(value: unknown): value is DeviceKind {
return typeof value === "string" && (DEVICE_KINDS as readonly string[]).includes(value);
}
function isScope(value: unknown): value is Scope {
return typeof value === "string" && (SCOPES as readonly string[]).includes(value);
}
function publicDevice(record: DeviceRecord): DevicePublic {
const { tokenHash: _tokenHash, ...rest } = record;
return { ...rest, scopes: [...rest.scopes] };
}
function pairCode(): string {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = randomBytes(8);
let code = "";
for (const byte of bytes) code += alphabet[byte % alphabet.length];
return code;
}
export class AuthStore {
readonly path: string;
private readonly now: () => number;
private readonly baseUrl: string;
private readonly touchIntervalMs: number;
private readonly devices: DeviceRecord[] = [];
private readonly pairs = new Map<string, PairEntry>();
constructor(options: AuthStoreOptions = {}) {
this.path = options.path ?? `${dataDir()}/devices.json`;
this.now = options.now ?? Date.now;
this.baseUrl = (options.baseUrl ?? "http://127.0.0.1:7676").replace(/\/+$/, "");
this.touchIntervalMs = options.touchIntervalMs ?? 60_000;
this.load();
}
createDevice(input: CreateDeviceInput): { token: string; device: DevicePublic } {
if (typeof input.name !== "string" || input.name.trim() === "") {
throw DaemonError.badRequest("device name is required");
}
if (!isDeviceKind(input.kind)) throw DaemonError.badRequest(`unknown device kind "${String(input.kind)}"`);
const scopes = input.scopes === undefined ? [...DEFAULT_SCOPES] : input.scopes.filter(isScope);
if (scopes.length === 0) scopes.push("read");
const token = randomBytes(32).toString("base64url");
const timestamp = this.now();
const record: DeviceRecord = {
id: `dev-${randomBytes(6).toString("hex")}`,
name: input.name.trim(),
kind: input.kind,
scopes,
tokenHash: hashToken(token),
createdAt: timestamp,
lastSeenAt: timestamp,
revokedAt: null,
};
this.devices.push(record);
this.persist();
return { token, device: publicDevice(record) };
}
verifyToken(rawToken: string): DevicePublic | null {
if (typeof rawToken !== "string" || rawToken.length === 0) return null;
const digest = hashToken(rawToken);
let matched: DeviceRecord | undefined;
// Compare against every record so the timing does not reveal the position.
for (const record of this.devices) {
if (timingSafeEqualHex(record.tokenHash, digest) && matched === undefined) matched = record;
}
if (!matched || matched.revokedAt !== null) return null;
return publicDevice(matched);
}
listDevices(): DevicePublic[] {
return this.devices.map(publicDevice);
}
revokeDevice(id: string): boolean {
const record = this.devices.find((device) => device.id === id);
if (!record || record.revokedAt !== null) return false;
record.revokedAt = this.now();
this.persist();
return true;
}
touchDevice(id: string): void {
const record = this.devices.find((device) => device.id === id);
if (!record) return;
const timestamp = this.now();
if (timestamp - record.lastSeenAt < this.touchIntervalMs) return;
record.lastSeenAt = timestamp;
this.persist();
}
pairCreate(options: { ttlSec?: number } = {}): PairCode {
const ttlSec = options.ttlSec ?? 600;
if (!Number.isFinite(ttlSec) || ttlSec <= 0) throw DaemonError.badRequest("ttlSec must be positive");
const timestamp = this.now();
this.prunePairs(timestamp);
const code = pairCode();
const nonce = randomBytes(16).toString("hex");
this.pairs.set(code, { code, nonce, expiresAt: timestamp + ttlSec * 1000, used: false });
return {
code,
url: `${this.baseUrl}/pair/${code}`,
expiresAt: timestamp + ttlSec * 1000,
nonce,
};
}
pairRedeem(input: RedeemPairInput): RedeemPairResult {
if (typeof input.code !== "string" || !/^[A-Z0-9]{8}$/.test(input.code)) {
throw DaemonError.unauthorized("invalid or already used pairing code");
}
if (!isDeviceKind(input.kind)) throw DaemonError.badRequest(`unknown device kind "${String(input.kind)}"`);
if (typeof input.deviceName !== "string" || input.deviceName.trim() === "") {
throw DaemonError.badRequest("deviceName is required");
}
const entry = this.pairs.get(input.code);
if (!entry || entry.used) throw DaemonError.unauthorized("invalid or already used pairing code");
const timestamp = this.now();
if (timestamp > entry.expiresAt) {
this.pairs.delete(entry.code);
throw DaemonError.unauthorized("pairing code expired");
}
entry.used = true;
this.pairs.delete(entry.code);
return this.createDevice({ name: input.deviceName, kind: input.kind });
}
/** Exposed for tests and diagnostics; never includes hashes. */
isPairing(code: string): boolean {
return this.pairs.has(code);
}
private prunePairs(timestamp: number): void {
for (const [code, entry] of this.pairs) {
if (entry.used || timestamp > entry.expiresAt) this.pairs.delete(code);
}
}
private load(): void {
if (!existsSync(this.path)) return;
const raw = readFileSync(this.path, "utf8");
if (raw.trim() === "") return;
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (error) {
throw new Error(`invalid device store ${this.path}: ${(error as Error).message}`);
}
const records = Array.isArray(parsed)
? parsed
: typeof parsed === "object" && parsed !== null && Array.isArray((parsed as PersistedDevices).devices)
? (parsed as PersistedDevices).devices
: [];
for (const value of records) {
if (typeof value !== "object" || value === null) continue;
const candidate = value as Partial<DeviceRecord>;
if (
typeof candidate.id !== "string" ||
typeof candidate.name !== "string" ||
!isDeviceKind(candidate.kind) ||
typeof candidate.tokenHash !== "string" ||
typeof candidate.createdAt !== "number"
) {
continue;
}
this.devices.push({
id: candidate.id,
name: candidate.name,
kind: candidate.kind,
scopes: Array.isArray(candidate.scopes) ? candidate.scopes.filter(isScope) : ["read"],
tokenHash: candidate.tokenHash,
createdAt: candidate.createdAt,
lastSeenAt: typeof candidate.lastSeenAt === "number" ? candidate.lastSeenAt : candidate.createdAt,
revokedAt: typeof candidate.revokedAt === "number" ? candidate.revokedAt : null,
});
}
}
private persist(): void {
const directory = dirname(this.path);
if (!existsSync(directory)) mkdirSync(directory, { recursive: true, mode: 0o700 });
const payload: PersistedDevices = { version: 1, devices: this.devices };
const temporary = `${this.path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
renameSync(temporary, this.path);
}
}
+94
View File
@@ -0,0 +1,94 @@
/** Daemon-side errors with a stable protocol code and HTTP status mapping. */
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import type { ErrorBody } from "../protocol/types.js";
const STATUS_BY_CODE: Record<string, number> = {
[ERROR_CODES.BAD_REQUEST]: 400,
[ERROR_CODES.UNAUTHORIZED]: 401,
[ERROR_CODES.FORBIDDEN]: 403,
[ERROR_CODES.NOT_FOUND]: 404,
[ERROR_CODES.METHOD_NOT_ALLOWED]: 405,
[ERROR_CODES.PROTOCOL_VERSION]: 426,
[ERROR_CODES.PAYLOAD_TOO_LARGE]: 413,
[ERROR_CODES.RATE_LIMITED]: 429,
[ERROR_CODES.INSTANCE_STARTING]: 409,
[ERROR_CODES.INSTANCE_UNMANAGED]: 409,
[ERROR_CODES.INSTANCE_UNAVAILABLE]: 503,
[ERROR_CODES.LEASE_CONFLICT]: 409,
[ERROR_CODES.EXTERNAL_SESSION]: 409,
[ERROR_CODES.SESSION_NOT_FOUND]: 404,
[ERROR_CODES.ATTENTION_RESOLVED]: 409,
[ERROR_CODES.UNSUPPORTED]: 501,
[ERROR_CODES.INTERNAL]: 500,
};
const RETRYABLE_CODES = new Set<string>([ERROR_CODES.INSTANCE_STARTING, ERROR_CODES.INSTANCE_UNAVAILABLE]);
export function statusForCode(code: string): number {
return STATUS_BY_CODE[code] ?? 500;
}
export function isRetryableCode(code: string): boolean {
return RETRYABLE_CODES.has(code);
}
export interface DaemonErrorOptions {
status?: number;
retryable?: boolean;
details?: Record<string, unknown>;
}
export class DaemonError extends Error {
readonly code: string;
readonly status: number;
readonly retryable: boolean;
readonly details: Record<string, unknown> | undefined;
constructor(code: string, message: string, options: DaemonErrorOptions = {}) {
super(message);
this.name = "DaemonError";
this.code = code;
this.status = options.status ?? statusForCode(code);
this.retryable = options.retryable ?? isRetryableCode(code);
this.details = options.details;
}
toBody(): ErrorBody {
return errorBody(this.code, this.message, this.retryable, this.details);
}
static from(error: unknown): DaemonError {
if (error instanceof DaemonError) return error;
if (error instanceof Error) return new DaemonError(ERROR_CODES.INTERNAL, error.message);
return new DaemonError(ERROR_CODES.INTERNAL, String(error));
}
static badRequest(message: string): DaemonError {
return new DaemonError(ERROR_CODES.BAD_REQUEST, message);
}
static unauthorized(message = "missing or invalid device token"): DaemonError {
return new DaemonError(ERROR_CODES.UNAUTHORIZED, message);
}
static forbidden(message = "origin is not allowed"): DaemonError {
return new DaemonError(ERROR_CODES.FORBIDDEN, message);
}
static notFound(message: string): DaemonError {
return new DaemonError(ERROR_CODES.NOT_FOUND, message);
}
static sessionNotFound(sessionId: string): DaemonError {
return new DaemonError(ERROR_CODES.SESSION_NOT_FOUND, `unknown session ${sessionId}`);
}
static payloadTooLarge(message: string): DaemonError {
return new DaemonError(ERROR_CODES.PAYLOAD_TOO_LARGE, message);
}
}
export function toErrorPayload(error: unknown): { status: number; body: ErrorBody } {
const daemonError = DaemonError.from(error);
return { status: daemonError.status, body: daemonError.toBody() };
}
+279
View File
@@ -0,0 +1,279 @@
/** Hono application factory for the daemon HTTP surface. */
import { existsSync } from "node:fs";
import { Hono, type Context } from "hono";
import type { HttpBindings } from "@hono/node-server";
import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/interfaces.js";
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
import type { Config } from "../config.js";
import type { AuthStore, DevicePublic } from "./auth.js";
import { isAllowedOrigin } from "./auth.js";
import { DaemonError, toErrorPayload } from "./errors.js";
import { CommandRouter } from "./router.js";
import { createSseHandler } from "./sse.js";
import { serveStatic } from "./static.js";
type Env = { Bindings: HttpBindings };
export interface DaemonMetrics {
connections: number;
eventsSent?: number;
eventRate?: number;
slowQueries?: number;
}
export interface AppDeps {
config: Config;
auth: AuthStore;
instances: InstanceManager;
workspaces: WorkspaceStore;
bus: Bus;
logger?: Logger;
daemonId: string;
machineId?: string;
startedAt?: number;
now?: () => number;
metrics?: () => DaemonMetrics;
}
function bearer(c: Context<Env>): string | undefined {
const header = c.req.header("authorization");
if (!header) return undefined;
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
return match?.[1]?.trim();
}
function isLoopback(c: Context<Env>): boolean {
const address = c.env?.incoming?.socket?.remoteAddress;
return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
}
function json(status: number, body: unknown, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json; charset=utf-8", ...headers },
});
}
async function readJsonBody(c: Context<Env>, maxBytes: number): Promise<Record<string, unknown>> {
const declared = c.req.header("content-length");
if (declared !== undefined) {
const length = Number(declared);
if (Number.isFinite(length) && length > maxBytes) {
throw DaemonError.payloadTooLarge(`body exceeds ${maxBytes} bytes`);
}
}
const text = await c.req.text();
if (Buffer.byteLength(text, "utf8") > maxBytes) {
throw DaemonError.payloadTooLarge(`body exceeds ${maxBytes} bytes`);
}
if (text.trim() === "") throw DaemonError.badRequest("request body is required");
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
throw DaemonError.badRequest("malformed JSON");
}
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
throw DaemonError.badRequest("body must be a JSON object");
}
return parsed as Record<string, unknown>;
}
function commandRequest(body: Record<string, unknown>): CommandRequest {
if (typeof body.method !== "string" || body.method.trim() === "") {
throw DaemonError.badRequest("method is required");
}
if (typeof body.v === "number" && body.v !== PROTOCOL_VERSION) {
throw new DaemonError(ERROR_CODES.PROTOCOL_VERSION, `unsupported protocol version ${body.v}`);
}
const request: CommandRequest = { method: body.method };
if (body.params !== undefined) {
if (typeof body.params !== "object" || body.params === null || Array.isArray(body.params)) {
throw DaemonError.badRequest("params must be an object");
}
request.params = body.params as Record<string, unknown>;
}
if (typeof body.sessionId === "string") request.sessionId = body.sessionId;
if (typeof body.clientRequestId === "string") request.clientRequestId = body.clientRequestId;
return request;
}
function publicDeviceOrThrow(c: Context<Env>, auth: AuthStore): DevicePublic {
const token = bearer(c);
const device = token ? auth.verifyToken(token) : null;
if (!device) throw DaemonError.unauthorized();
auth.touchDevice(device.id);
return device;
}
export function createApp(deps: AppDeps): Hono<Env> {
const { config, auth, instances, workspaces, bus, logger } = deps;
const now = deps.now ?? Date.now;
const startedAt = deps.startedAt ?? now();
const app = new Hono<Env>();
const router = new CommandRouter({ auth, instances, workspaces, logger, now, daemonId: deps.daemonId });
// Origin check + CORS. Applies to every surface, including SSE.
app.use("*", async (c, next) => {
const origin = c.req.header("origin");
if (!isAllowedOrigin(origin, config.corsOrigins)) {
return json(403, errorBody(ERROR_CODES.FORBIDDEN, "origin is not allowed"));
}
if (origin) {
c.header("Access-Control-Allow-Origin", origin);
c.header("Vary", "Origin");
}
if (c.req.method.toUpperCase() === "OPTIONS") {
c.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
c.header("Access-Control-Allow-Headers", "authorization, content-type");
c.header("Access-Control-Max-Age", "600");
return c.body(null, 204);
}
await next();
});
app.use("/api/*", async (c, next) => {
const path = new URL(c.req.url).pathname;
if (path === "/api/v1/info" || path === "/api/v1/health") {
if (isLoopback(c)) return next();
}
// Pairing redeem is public; pair.create enforces auth in its handler.
if (path === "/api/v1/pair") return next();
const token = bearer(c);
const device = token ? auth.verifyToken(token) : null;
if (!device) {
return json(401, errorBody(ERROR_CODES.UNAUTHORIZED, "missing or invalid device token"));
}
auth.touchDevice(device.id);
await next();
});
app.get("/api/v1/info", (c) =>
c.json({
v: PROTOCOL_VERSION,
daemonId: deps.daemonId,
machineId: deps.machineId ?? deps.daemonId,
platform: process.platform,
capabilities: ["ws", "sse", "devices", "attention"],
limits: config.limits,
}),
);
const health = (c: Context<Env>) => {
const items = [
{ name: "instances", ok: true, detail: `${instances.list().length} connected` },
{ name: "workspaces", ok: true, detail: `${workspaces.list().length} registered` },
{ name: "auth", ok: true, detail: `${auth.listDevices().length} devices` },
{ name: "static", ok: existsSync(config.staticDir), detail: config.staticDir },
];
return c.json({ ok: items.every((item) => item.ok), items });
};
app.get("/api/v1/health", health);
app.get("/health", health);
app.get("/api/v1/workspaces", (c) => c.json(workspaces.list()));
app.get("/api/v1/workspaces/:id/sessions", async (c) => {
const workspaceId = c.req.param("id");
if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`);
const ack = await router.relayWorkspaceQuery(workspaceId, "sessions");
return json(200, ack);
});
app.get("/api/v1/sessions/:sid/entries", async (c) => {
const params: Record<string, unknown> = {};
const before = c.req.query("before");
if (before !== undefined) params.before = before;
const limit = Number(c.req.query("limit"));
if (Number.isFinite(limit) && limit > 0) params.limit = Math.min(500, Math.floor(limit));
const ack = await router.relaySessionQuery(c.req.param("sid"), "session.entries", params);
return json(200, ack);
});
app.get("/api/v1/attention", async (c) => {
const workspaceId = c.req.query("workspaceId");
if (!workspaceId) throw DaemonError.badRequest("workspaceId is required");
if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`);
const ack = await router.relayWorkspaceQuery(workspaceId, "attention");
return json(200, ack);
});
app.get("/api/v1/models", async (c) => {
const workspaceId = c.req.query("workspaceId");
if (!workspaceId) throw DaemonError.badRequest("workspaceId is required");
if (!workspaces.get(workspaceId)) throw DaemonError.notFound(`unknown workspace ${workspaceId}`);
const ack = await router.relayWorkspaceQuery(workspaceId, "models");
return json(200, ack);
});
app.get("/api/v1/devices", (c) => c.json(auth.listDevices()));
app.delete("/api/v1/devices/:id", (c) => {
const id = c.req.param("id");
if (!auth.revokeDevice(id)) throw new DaemonError(ERROR_CODES.NOT_FOUND, `unknown device ${id}`);
return c.body(null, 204);
});
app.get("/api/v1/resources", async (c) => c.json(await instances.resources()));
app.get("/api/v1/diagnostics", (c) => {
const metrics = deps.metrics?.() ?? { connections: 0 };
return c.json({
v: PROTOCOL_VERSION,
daemonId: deps.daemonId,
uptimeMs: now() - startedAt,
connections: metrics.connections,
eventsSent: metrics.eventsSent ?? 0,
eventRate: metrics.eventRate ?? 0,
slowQueries: metrics.slowQueries ?? 0,
devices: auth.listDevices().length,
workspaces: workspaces.list().length,
instances: instances.list(),
});
});
app.post("/api/v1/cmd", async (c) => {
if (!bearer(c)) throw DaemonError.unauthorized();
const body = await readJsonBody(c, config.limits.maxBodyBytes);
const result = await router.dispatch(commandRequest(body));
return json(result.status, result.body);
});
app.post("/api/v1/pair", async (c) => {
const body = await readJsonBody(c, config.limits.maxBodyBytes);
if (typeof body.code === "string") {
if (typeof body.kind !== "string") throw DaemonError.badRequest("kind is required");
const redeemed = auth.pairRedeem({
code: body.code,
deviceName: typeof body.deviceName === "string" ? body.deviceName : "",
kind: body.kind as "phone" | "laptop" | "tablet",
});
return c.json({ token: redeemed.token, device: redeemed.device });
}
publicDeviceOrThrow(c, auth);
const ttlSec = typeof body.ttlSec === "number" ? body.ttlSec : undefined;
const pair = auth.pairCreate(ttlSec === undefined ? {} : { ttlSec });
return c.json({ accepted: true, ...pair });
});
app.get("/events", createSseHandler({ auth, bus, corsOrigins: config.corsOrigins, logger }));
app.all("*", async (c) => {
const path = new URL(c.req.url).pathname;
if (path === "/api" || path.startsWith("/api/") || path === "/ws" || path.startsWith("/ws/")) {
return json(404, errorBody(ERROR_CODES.NOT_FOUND, "not found"));
}
if (c.req.method !== "GET" && c.req.method !== "HEAD") {
return json(405, errorBody(ERROR_CODES.METHOD_NOT_ALLOWED, "method not allowed"));
}
return serveStatic(c, config.staticDir);
});
app.onError((error, c) => {
const mapped = toErrorPayload(error);
return json(mapped.status, mapped.body);
});
return app;
}
+53
View File
@@ -0,0 +1,53 @@
/** In-process event bus with failure isolation for subscriber handlers. */
import type { Bus, Logger } from "../core/interfaces.js";
export interface InMemoryBusOptions {
logger?: Logger;
slowHandlerMs?: number;
}
type Handler = (record: Record<string, unknown>) => void;
export class InMemoryBus implements Bus {
private readonly handlers = new Set<Handler>();
private readonly logger: Logger | undefined;
private readonly slowHandlerMs: number;
constructor(options: InMemoryBusOptions = {}) {
this.logger = options.logger;
this.slowHandlerMs = options.slowHandlerMs ?? 50;
}
publish(record: Record<string, unknown>): void {
for (const handler of this.handlers) {
const started = performance.now();
try {
handler(record);
} catch (error) {
this.logger?.warn("bus handler threw", {
type: record.type,
error: error instanceof Error ? error.message : String(error),
});
}
const elapsed = performance.now() - started;
if (elapsed > this.slowHandlerMs) {
this.logger?.warn("slow bus handler", {
type: record.type,
elapsedMs: Math.round(elapsed),
budgetMs: this.slowHandlerMs,
});
}
}
}
subscribe(handler: Handler): () => void {
this.handlers.add(handler);
return () => {
this.handlers.delete(handler);
};
}
get subscriberCount(): number {
return this.handlers.size;
}
}
+296
View File
@@ -0,0 +1,296 @@
/**
* Command routing for `POST /api/v1/cmd` (and the read relays used by REST).
*
* The daemon owns `workspace.*`, `instance.*`, `pair.*`, `device.revoke` and
* `system.*`; everything else is forwarded to the plugin that owns the session.
*/
import { randomUUID } from "node:crypto";
import type { InstanceManager, Logger, WorkspaceStore } from "../core/interfaces.js";
import { ERROR_CODES } from "../protocol/errors.js";
import type { CommandRequest } from "../protocol/types.js";
import type { AuthStore, DeviceKind } from "./auth.js";
import { DaemonError, toErrorPayload } from "./errors.js";
const DEDUPE_TTL_MS = 5 * 60 * 1000;
export interface RouterDeps {
auth: AuthStore;
instances: InstanceManager;
workspaces: WorkspaceStore;
logger?: Logger;
now?: () => number;
daemonId?: string;
}
export interface CommandResult {
status: number;
body: Record<string, unknown>;
}
interface CacheEntry {
status: number;
body: Record<string, unknown>;
expiresAt: number;
}
function asParams(request: CommandRequest): Record<string, unknown> {
if (request.params === undefined) return {};
if (typeof request.params !== "object" || request.params === null || Array.isArray(request.params)) {
throw DaemonError.badRequest("params must be an object");
}
return request.params;
}
function requireString(params: Record<string, unknown>, key: string, label = key): string {
const value = params[key];
if (typeof value !== "string" || value.trim() === "") {
throw DaemonError.badRequest(`${label} is required`);
}
return value;
}
function optionalString(params: Record<string, unknown>, key: string): string | undefined {
const value = params[key];
return typeof value === "string" && value.trim() !== "" ? value : undefined;
}
export class CommandRouter {
private readonly auth: AuthStore;
private readonly instances: InstanceManager;
private readonly workspaces: WorkspaceStore;
private readonly logger: Logger | undefined;
private readonly now: () => number;
private readonly dedupe = new Map<string, CacheEntry>();
private readonly inFlight = new Map<string, Promise<CommandResult>>();
constructor(deps: RouterDeps) {
this.auth = deps.auth;
this.instances = deps.instances;
this.workspaces = deps.workspaces;
this.logger = deps.logger;
this.now = deps.now ?? Date.now;
}
async dispatch(request: CommandRequest): Promise<CommandResult> {
if (typeof request !== "object" || request === null || typeof request.method !== "string") {
const mapped = toErrorPayload(DaemonError.badRequest("method is required"));
return { status: mapped.status, body: mapped.body as unknown as Record<string, unknown> };
}
const clientRequestId = request.clientRequestId;
if (typeof clientRequestId !== "string" || clientRequestId === "") {
return this.execute(request);
}
const key = `${request.method}\u0000${clientRequestId}`;
const cached = this.dedupe.get(key);
if (cached) {
if (cached.expiresAt > this.now()) {
return { status: cached.status, body: cached.body };
}
this.dedupe.delete(key);
}
const running = this.inFlight.get(key);
if (running) return running;
const promise = this.execute(request)
.then((result) => {
if (result.status === 202) {
this.dedupe.set(key, {
status: result.status,
body: result.body,
expiresAt: this.now() + DEDUPE_TTL_MS,
});
}
return result;
})
.finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
}
/** Relayed read used by `GET /workspaces/:id/sessions`, `/attention`, `/models`. */
async relayWorkspaceQuery(
workspaceId: string,
kind: string,
params: Record<string, unknown> = {},
): Promise<Record<string, unknown>> {
if (typeof workspaceId !== "string" || workspaceId === "") {
throw DaemonError.badRequest("workspaceId is required");
}
return this.relay(workspaceId, undefined, "workspace.query", { ...params, kind });
}
/** Relayed read used by `GET /sessions/:sid/entries`. */
async relaySessionQuery(
sessionId: string,
method: string,
params: Record<string, unknown> = {},
): Promise<Record<string, unknown>> {
const workspaceId = this.resolveWorkspace(sessionId, params);
return this.relay(workspaceId, sessionId, method, params);
}
private async relay(
workspaceId: string,
sessionId: string | undefined,
method: string,
params: Record<string, unknown>,
clientRequestId?: string,
): Promise<Record<string, unknown>> {
await this.instances.ensure(workspaceId);
const connection = this.instances.get(workspaceId);
if (!connection) {
throw new DaemonError(ERROR_CODES.INSTANCE_UNAVAILABLE, `no instance for workspace ${workspaceId}`, {
retryable: true,
});
}
const ack = await connection.command({
id: `req-${randomUUID()}`,
...(sessionId === undefined ? {} : { sessionId }),
method,
params,
...(clientRequestId === undefined ? {} : { clientRequestId }),
});
return ack as unknown as Record<string, unknown>;
}
private async execute(request: CommandRequest): Promise<CommandResult> {
try {
const params = asParams(request);
const method = request.method;
if (method.startsWith("workspace.")) {
const result = await this.workspaceCommand(method, params);
if (result) return { status: 202, body: result };
if (method !== "workspace.query") {
throw new DaemonError(ERROR_CODES.UNSUPPORTED, `unsupported daemon method ${method}`);
}
}
if (method === "instance.ensure") {
const workspaceId = requireString(params, "workspaceId");
const state = await this.instances.ensure(workspaceId);
return { status: 202, body: { accepted: true, instance: state } };
}
if (method === "instance.shutdown") {
const workspaceId = requireString(params, "workspaceId");
const mode = params.mode === "stop" ? "stop" : "drain";
await this.instances.shutdown(workspaceId, mode);
return { status: 202, body: { accepted: true, workspaceId, mode } };
}
if (method === "system.doctor") {
return {
status: 202,
body: { accepted: true, ok: true, instances: this.instances.list() },
};
}
if (method === "system.shutdown") {
const instances = this.instances.list();
for (const instance of instances) {
await this.instances.shutdown(instance.workspaceId, "stop");
}
return { status: 202, body: { accepted: true, stopped: instances.length } };
}
if (method.startsWith("system.") || method.startsWith("instance.")) {
throw new DaemonError(ERROR_CODES.UNSUPPORTED, `unsupported daemon method ${method}`);
}
if (method === "pair.create") {
const ttlSec = typeof params.ttlSec === "number" ? params.ttlSec : undefined;
const pair = this.auth.pairCreate(ttlSec === undefined ? {} : { ttlSec });
return { status: 202, body: { accepted: true, ...pair } };
}
if (method === "pair.redeem") {
const redeemed = this.auth.pairRedeem({
code: requireString(params, "code"),
deviceName: requireString(params, "deviceName"),
kind: requireString(params, "kind") as DeviceKind,
});
return { status: 202, body: { accepted: true, token: redeemed.token, device: redeemed.device } };
}
if (method === "device.revoke") {
const deviceId = optionalString(params, "deviceId") ?? optionalString(params, "id");
if (!deviceId) throw DaemonError.badRequest("deviceId is required");
if (!this.auth.revokeDevice(deviceId)) {
throw new DaemonError(ERROR_CODES.NOT_FOUND, `unknown device ${deviceId}`);
}
return { status: 202, body: { accepted: true, revoked: true, deviceId } };
}
const workspaceId = this.resolveWorkspace(request.sessionId, params);
const ack = await this.relay(
workspaceId,
request.sessionId,
method,
params,
request.clientRequestId,
);
return { status: 202, body: { accepted: true, ...ack } };
} catch (error) {
this.logger?.debug("command failed", {
method: request.method,
error: error instanceof Error ? error.message : String(error),
});
const mapped = toErrorPayload(error);
return { status: mapped.status, body: mapped.body as unknown as Record<string, unknown> };
}
}
private async workspaceCommand(
method: string,
params: Record<string, unknown>,
): Promise<Record<string, unknown> | undefined> {
switch (method) {
case "workspace.add": {
const input: { cwd: string; alias?: string; trust?: boolean } = {
cwd: requireString(params, "cwd"),
};
const alias = optionalString(params, "alias");
if (alias !== undefined) input.alias = alias;
if (typeof params.trust === "boolean") input.trust = params.trust;
const workspace = await this.workspaces.add(input);
return { accepted: true, workspace };
}
case "workspace.update": {
const workspaceId = requireString(params, "workspaceId");
const patch =
typeof params.patch === "object" && params.patch !== null
? (params.patch as Partial<{ alias: string | null; pinned: boolean; hidden: boolean; trusted: boolean }>)
: {};
const workspace = await this.workspaces.update(workspaceId, patch);
return { accepted: true, workspace };
}
case "workspace.remove": {
const workspaceId = requireString(params, "workspaceId");
await this.workspaces.remove(workspaceId);
return { accepted: true, workspaceId };
}
case "workspace.refresh": {
const workspaceId = optionalString(params, "workspaceId");
await this.workspaces.refresh(workspaceId);
return { accepted: true, ...(workspaceId === undefined ? {} : { workspaceId }) };
}
default:
// `workspace.query` and unknown workspace.* methods fall through to the plugin.
return undefined;
}
}
private resolveWorkspace(sessionId: string | undefined, params: Record<string, unknown>): string {
const explicit = optionalString(params, "workspaceId");
if (sessionId !== undefined && sessionId !== "") {
const owner = this.instances.findWorkspaceBySession(sessionId);
if (owner) return owner;
if (explicit) return explicit;
throw DaemonError.sessionNotFound(sessionId);
}
if (explicit) return explicit;
throw DaemonError.badRequest("workspaceId or sessionId is required");
}
}
export function createRouter(deps: RouterDeps): CommandRouter {
return new CommandRouter(deps);
}
+125
View File
@@ -0,0 +1,125 @@
/** Node HTTP server wiring: Hono fetch handler + WS upgrade on the same port. */
import { createServer, type Server } from "node:http";
import { getRequestListener, type HttpBindings } from "@hono/node-server";
import type { Hono } from "hono";
import type { Config } from "../config.js";
import type { AppDeps } from "./http.js";
import { createApp } from "./http.js";
import { attachWsServer, type WsServerHandle } from "./ws.js";
export interface WsServerOverrides {
heartbeatMs?: number;
authTimeoutMs?: number;
maxBufferedBytes?: number;
closeBufferedBytes?: number;
maxConnections?: number;
measureBufferedAmount?: (socket: import("ws").WebSocket) => number;
}
export type ServerDeps = Omit<AppDeps, "config" | "metrics"> & {
heartbeatMs?: number;
ws?: WsServerOverrides;
};
export interface StartedServer {
server: Server;
url: string;
port: number;
config: Config;
ws: WsServerHandle;
close(): Promise<void>;
}
function hostForUrl(host: string): string {
if (host === "" || host === "0.0.0.0" || host === "::") return "127.0.0.1";
return host.includes(":") ? `[${host}]` : host;
}
export async function startServer(config: Config, deps: ServerDeps): Promise<StartedServer> {
let app: Hono<{ Bindings: HttpBindings }> | undefined;
const listener = getRequestListener((request, env) => {
if (!app) return new Response("daemon starting", { status: 503 });
return app.fetch(request, env as never);
});
const server = createServer(listener);
await new Promise<void>((resolve, reject) => {
const onError = (error: Error): void => {
server.off("listening", onListening);
reject(error);
};
const onListening = (): void => {
server.off("error", onError);
resolve();
};
server.once("error", onError);
server.once("listening", onListening);
server.listen(config.port, config.host);
});
const address = server.address();
const port = typeof address === "object" && address !== null ? address.port : config.port;
const effectiveConfig: Config =
port === config.port
? config
: {
...config,
port,
corsOrigins: config.corsOrigins.map((origin) =>
origin.endsWith(`:${config.port}`) ? `${origin.slice(0, -String(config.port).length)}${port}` : origin,
),
};
const wsOverrides = deps.ws ?? {};
const ws = attachWsServer({
server,
config: effectiveConfig,
auth: deps.auth,
instances: deps.instances,
bus: deps.bus,
logger: deps.logger,
daemonId: deps.daemonId,
now: deps.now,
heartbeatMs: wsOverrides.heartbeatMs ?? deps.heartbeatMs,
authTimeoutMs: wsOverrides.authTimeoutMs,
maxBufferedBytes: wsOverrides.maxBufferedBytes,
closeBufferedBytes: wsOverrides.closeBufferedBytes,
maxConnections: wsOverrides.maxConnections,
measureBufferedAmount: wsOverrides.measureBufferedAmount,
});
app = createApp({
config: effectiveConfig,
auth: deps.auth,
instances: deps.instances,
workspaces: deps.workspaces,
bus: deps.bus,
logger: deps.logger,
daemonId: deps.daemonId,
machineId: deps.machineId,
startedAt: deps.startedAt,
now: deps.now,
metrics: () => ({ connections: ws.connections(), eventsSent: ws.eventsSent() }),
});
let closing: Promise<void> | undefined;
const close = (): Promise<void> => {
if (closing) return closing;
closing = (async () => {
await ws.close();
const stopped = new Promise<void>((resolve) => server.close(() => resolve()));
server.closeAllConnections();
await stopped;
})();
return closing;
};
return {
server,
url: `http://${hostForUrl(config.host)}:${port}`,
port,
config: effectiveConfig,
ws,
close,
};
}
+85
View File
@@ -0,0 +1,85 @@
/**
* SSE fallback (`GET /events`).
*
* The browser can pass the device token as `?token=` here only (a browser
* `EventSource` cannot set headers). Events are filtered by repeated
* `sessionId` query parameters.
*/
import type { Context } from "hono";
import { streamSSE } from "hono/streaming";
import type { Bus, Logger } from "../core/interfaces.js";
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { isAllowedOrigin, type AuthStore } from "./auth.js";
export interface SseDeps {
auth: AuthStore;
bus: Bus;
corsOrigins: readonly string[];
logger?: Logger;
now?: () => number;
heartbeatMs?: number;
}
function json(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json; charset=utf-8" },
});
}
export function createSseHandler(deps: SseDeps): (c: Context) => Promise<Response> {
const { auth, bus, corsOrigins, logger, heartbeatMs = 15_000 } = deps;
return async (c: Context): Promise<Response> => {
const origin = c.req.header("origin");
if (!isAllowedOrigin(origin, corsOrigins)) {
return json(403, errorBody(ERROR_CODES.FORBIDDEN, "origin is not allowed"));
}
const queryToken = c.req.query("token");
const header = c.req.header("authorization");
const headerToken = header?.replace(/^Bearer\s+/i, "").trim();
const device = auth.verifyToken(queryToken ?? headerToken ?? "");
if (!device) return json(401, errorBody(ERROR_CODES.UNAUTHORIZED, "missing or invalid device token"));
auth.touchDevice(device.id);
const sessions = new Set(c.req.queries("sessionId") ?? []);
const workspaceId = c.req.query("workspaceId");
return streamSSE(
c,
async (stream) => {
const unsubscribe = bus.subscribe((record) => {
if (record.type !== "event") return;
if (sessions.size > 0 && (typeof record.sessionId !== "string" || !sessions.has(record.sessionId))) return;
if (workspaceId && record.workspaceId !== workspaceId) return;
void stream
.writeSSE({ data: JSON.stringify(record) })
.catch((error) =>
logger?.debug("sse write failed", {
error: error instanceof Error ? error.message : String(error),
}),
);
});
const heartbeat = setInterval(() => {
void stream
.write(": heartbeat\n\n")
.catch(() => undefined);
}, heartbeatMs);
heartbeat.unref?.();
await new Promise<void>((resolve) => {
stream.onAbort(() => {
clearInterval(heartbeat);
unsubscribe();
resolve();
});
});
},
async (error) => {
logger?.debug("sse stream failed", { error: error.message });
},
);
};
}
+188
View File
@@ -0,0 +1,188 @@
/**
* Static UI serving.
*
* Hashed assets are immutable; `index.html` is never cached. Unknown
* extension-less paths are SPA routes and fall back to `index.html`, while
* `/api*`, `/ws*`, asset paths and file-looking paths return 404.
*/
import { readFileSync, realpathSync, statSync } from "node:fs";
import { extname, join, sep } from "node:path";
import type { Context } from "hono";
import { errorBody, ERROR_CODES } from "../protocol/errors.js";
const CONTENT_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".map": "application/json; charset=utf-8",
".txt": "text/plain; charset=utf-8",
".wasm": "application/wasm",
};
export type StaticKind = "file" | "not_found" | "method_not_allowed";
export interface StaticResolution {
kind: StaticKind;
status: number;
filePath?: string;
headers: Record<string, string>;
}
const NO_STORE = "no-store";
const IMMUTABLE = "public, max-age=31536000, immutable";
const REVALIDATE = "no-cache";
function json(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json; charset=utf-8" },
});
}
function isReservedPath(pathname: string): boolean {
return (
pathname === "/api" ||
pathname.startsWith("/api/") ||
pathname === "/ws" ||
pathname.startsWith("/ws/")
);
}
function notFound(): StaticResolution {
return { kind: "not_found", status: 404, headers: {} };
}
function fileResolution(filePath: string, relativePath: string): StaticResolution {
const cacheControl =
relativePath === "index.html"
? NO_STORE
: relativePath.startsWith("assets/")
? IMMUTABLE
: REVALIDATE;
const type = CONTENT_TYPES[extname(filePath).toLowerCase()] ?? "application/octet-stream";
let size = 0;
try {
size = statSync(filePath).size;
} catch {
return notFound();
}
return {
kind: "file",
status: 200,
filePath,
headers: {
"content-type": type,
"content-length": String(size),
"cache-control": cacheControl,
"x-content-type-options": "nosniff",
},
};
}
function safeRealRoot(staticDir: string): string | undefined {
try {
return realpathSync(staticDir);
} catch {
return undefined;
}
}
function indexFile(root: string, staticDir: string): StaticResolution {
const indexPath = join(staticDir, "index.html");
let realIndex: string;
try {
realIndex = realpathSync(indexPath);
} catch {
return notFound();
}
if (realIndex !== root && !realIndex.startsWith(`${root}${sep}`)) return notFound();
return fileResolution(realIndex, "index.html");
}
/**
* Resolve a request path without touching the network. Exported so the logic
* can be unit-tested independently of the Hono adapter.
*/
export function resolveStaticRequest(staticDir: string, rawPath: string, rawMethod: string): StaticResolution {
const method = rawMethod.toUpperCase();
if (method !== "GET" && method !== "HEAD") {
return { kind: "method_not_allowed", status: 405, headers: { allow: "GET, HEAD" } };
}
const withoutQuery = rawPath.split("?")[0] ?? "/";
let pathname: string;
try {
pathname = decodeURIComponent(withoutQuery);
} catch {
return notFound();
}
if (pathname.includes("\0")) return notFound();
if (!pathname.startsWith("/")) pathname = `/${pathname}`;
if (isReservedPath(pathname)) return notFound();
const segments = pathname.split("/").filter((segment) => segment.length > 0);
if (segments.some((segment) => segment === "..")) return notFound();
const root = safeRealRoot(staticDir);
if (!root) return notFound();
const relativePath = segments.join("/");
if (relativePath === "") return indexFile(root, staticDir);
const directPath = join(staticDir, relativePath);
let realDirect: string;
try {
realDirect = realpathSync(directPath);
} catch {
// Missing path: SPA fallback unless it looks like an asset or a file.
if (relativePath.startsWith("assets/")) return notFound();
if (extname(relativePath) !== "") return notFound();
return indexFile(root, staticDir);
}
if (realDirect !== root && !realDirect.startsWith(`${root}${sep}`)) return notFound();
try {
if (statSync(realDirect).isDirectory()) {
return indexFile(root, staticDir);
}
} catch {
return notFound();
}
return fileResolution(realDirect, relativePath);
}
export async function serveStatic(c: Context, staticDir: string): Promise<Response> {
const method = c.req.method.toUpperCase();
const resolution = resolveStaticRequest(staticDir, new URL(c.req.url).pathname, method);
if (resolution.kind === "method_not_allowed") {
return json(405, errorBody(ERROR_CODES.METHOD_NOT_ALLOWED, "static files support GET and HEAD only"));
}
if (resolution.kind === "not_found" || !resolution.filePath) {
return json(404, errorBody(ERROR_CODES.NOT_FOUND, "not found"));
}
let body: Buffer | null = null;
try {
body = readFileSync(resolution.filePath);
} catch {
return json(404, errorBody(ERROR_CODES.NOT_FOUND, "not found"));
}
return new Response(method === "HEAD" ? null : new Uint8Array(body), {
status: 200,
headers: resolution.headers,
});
}
+513
View File
@@ -0,0 +1,513 @@
/**
* Browser WebSocket surface (`/ws`).
*
* Auth happens in the first message (`{type:"auth",token}`) or via an
* `Authorization: Bearer` upgrade header. Subscriptions fan records out from
* the daemon bus; every connection has a bounded write buffer.
*/
import type { Server } from "node:http";
import type { Duplex } from "node:stream";
import { WebSocket, WebSocketServer, type RawData } from "ws";
import type { Bus, InstanceManager, Logger } from "../core/interfaces.js";
import type { InstanceState, SessionState } from "../protocol/types.js";
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { isAllowedOrigin, type AuthStore, type DevicePublic } from "./auth.js";
import type { Config } from "../config.js";
import { toErrorPayload } from "./errors.js";
const SERVER_TYPES = new Set([
"hello_ack",
"instance_state",
"workspace_update",
"snapshot",
"event",
"presence",
"resync_required",
"error",
]);
const CLOSE_UNAUTHORIZED = 4401;
const CLOSE_BAD_MESSAGE = 4400;
const CLOSE_TRY_AGAIN = 1013;
export interface WsServerOptions {
server: Server;
config: Config;
auth: AuthStore;
instances: InstanceManager;
bus: Bus;
logger?: Logger;
daemonId?: string;
now?: () => number;
heartbeatMs?: number;
authTimeoutMs?: number;
maxBufferedBytes?: number;
closeBufferedBytes?: number;
maxConnections?: number;
measureBufferedAmount?: (socket: WebSocket) => number;
}
export interface WsServerHandle {
wss: WebSocketServer;
connections(): number;
eventsSent(): number;
close(): Promise<void>;
}
interface PendingSince {
sessionId: string;
epoch: string;
seq: number;
}
interface ClientState {
ws: WebSocket;
device: DevicePublic | null;
authenticated: boolean;
workspaceIds: Set<string>;
sessionWorkspaces: Map<string, string>;
alive: boolean;
dropped: boolean;
authTimer: NodeJS.Timeout | undefined;
}
function writeUpgradeRejection(socket: Duplex, status: number, code: string, message: string): void {
const body = JSON.stringify(errorBody(code, message));
const reason = status === 403 ? "Forbidden" : status === 401 ? "Unauthorized" : status === 404 ? "Not Found" : "Service Unavailable";
socket.end(
`HTTP/1.1 ${status} ${reason}\r\n` +
"Connection: close\r\n" +
"Content-Type: application/json; charset=utf-8\r\n" +
`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n` +
body,
);
}
function bearerToken(header: string | string[] | undefined): string | undefined {
const value = Array.isArray(header) ? header[0] : header;
if (typeof value !== "string") return undefined;
const match = /^Bearer\s+(.+)$/i.exec(value.trim());
return match?.[1]?.trim();
}
export function attachWsServer(options: WsServerOptions): WsServerHandle {
const {
server,
config,
auth,
instances,
bus,
logger,
daemonId = "d-local",
now = Date.now,
heartbeatMs = 30_000,
authTimeoutMs = 10_000,
maxBufferedBytes = 4 * 1024 * 1024,
closeBufferedBytes = 8 * 1024 * 1024,
maxConnections = config.limits.maxConnections,
measureBufferedAmount = (socket: WebSocket) => socket.bufferedAmount,
} = options;
const wss = new WebSocketServer({ noServer: true, maxPayload: config.limits.maxFrameBytes });
const clients = new Set<ClientState>();
let eventsSent = 0;
let closed = false;
const send = (state: ClientState, record: Record<string, unknown>): void => {
if (state.ws.readyState !== WebSocket.OPEN) return;
try {
state.ws.send(JSON.stringify(record));
} catch (error) {
logger?.debug("ws send failed", { error: error instanceof Error ? error.message : String(error) });
}
};
const sendError = (state: ClientState, code: string, message: string): void => {
send(state, { v: 1, type: "error", payload: errorBody(code, message) });
};
const sendEvent = (state: ClientState, record: Record<string, unknown>): void => {
if (state.ws.readyState !== WebSocket.OPEN) return;
let buffered: number;
try {
buffered = measureBufferedAmount(state.ws);
} catch {
buffered = state.ws.bufferedAmount;
}
if (buffered > closeBufferedBytes) {
state.ws.close(CLOSE_TRY_AGAIN, "buffer overflow");
return;
}
if (buffered > maxBufferedBytes) {
if (!state.dropped) {
state.dropped = true;
send(state, { v: 1, type: "dropped", payload: { reason: "backpressure" }, ts: now() });
}
return;
}
state.dropped = false;
eventsSent += 1;
send(state, record);
};
const hello = (state: ClientState): void => {
if (!state.device) return;
send(state, {
v: 1,
type: "hello_ack",
daemonId,
limits: { maxFrameBytes: config.limits.maxFrameBytes },
device: {
id: state.device.id,
name: state.device.name,
kind: state.device.kind,
scopes: state.device.scopes,
},
});
};
const authenticate = (state: ClientState, token: string | undefined): boolean => {
if (!token) return false;
const device = auth.verifyToken(token);
if (!device) return false;
state.device = device;
state.authenticated = true;
state.alive = true;
if (state.authTimer) {
clearTimeout(state.authTimer);
state.authTimer = undefined;
}
auth.touchDevice(device.id);
hello(state);
return true;
};
const releaseSession = (state: ClientState, sessionId: string): void => {
const workspaceId = state.sessionWorkspaces.get(sessionId);
state.sessionWorkspaces.delete(sessionId);
if (!workspaceId) return;
const others = [...clients].some(
(other) => other !== state && other.authenticated && other.sessionWorkspaces.has(sessionId),
);
if (others) return;
const connection = instances.get(workspaceId);
connection?.unsubscribe(sessionId);
instances.maybeUnsubscribe(workspaceId, sessionId);
};
const epochFor = (workspaceId: string, state: InstanceState | undefined): string => {
if (state) return state.instanceId;
return instances.list().find((candidate) => candidate.workspaceId === workspaceId)?.instanceId ?? workspaceId;
};
const sendSnapshot = (
state: ClientState,
sessionId: string,
epoch: string,
seq: number,
snapshot: SessionState,
): void => {
send(state, {
v: 1,
type: "snapshot",
sessionId,
epoch,
seq,
ts: now(),
payload: { state: snapshot },
});
};
const subscribeSession = async (
state: ClientState,
sessionId: string,
workspaceHint: string | undefined,
since: PendingSince | undefined,
): Promise<void> => {
if (typeof sessionId !== "string" || sessionId === "") {
sendError(state, ERROR_CODES.BAD_REQUEST, "sessionId is required");
return;
}
const workspaceId = workspaceHint ?? instances.findWorkspaceBySession(sessionId);
if (!workspaceId) {
sendError(state, ERROR_CODES.SESSION_NOT_FOUND, `unknown session ${sessionId}`);
return;
}
state.sessionWorkspaces.set(sessionId, workspaceId);
const instanceState = await instances.ensure(workspaceId);
const connection = instances.get(workspaceId);
if (!connection) {
sendError(state, ERROR_CODES.INSTANCE_UNAVAILABLE, `no instance for workspace ${workspaceId}`);
return;
}
connection.subscribe(sessionId);
const epoch = epochFor(workspaceId, instanceState);
const lastSeq = connection.lastSeq(sessionId);
if (since) {
if (since.epoch !== epoch || since.seq > lastSeq) {
send(state, {
v: 1,
type: "resync_required",
sessionId,
epoch,
seq: lastSeq,
payload: { requestedEpoch: since.epoch, requestedSeq: since.seq, lastSeq },
});
return;
}
}
const snapshot = connection.snapshot(sessionId);
if (snapshot) sendSnapshot(state, sessionId, epoch, lastSeq, snapshot);
};
const subscribe = async (state: ClientState, payload: Record<string, unknown>): Promise<void> => {
const workspaceId = typeof payload.workspaceId === "string" ? payload.workspaceId : undefined;
const workspaceHint = typeof payload.workspaceId === "string" ? payload.workspaceId : undefined;
if (workspaceId) {
state.workspaceIds.add(workspaceId);
await instances.ensure(workspaceId);
}
const sessionIds = Array.isArray(payload.sessionIds)
? payload.sessionIds.filter((value): value is string => typeof value === "string")
: [];
if (typeof payload.sessionId === "string") sessionIds.push(payload.sessionId);
let since: PendingSince | undefined;
if (typeof payload.since === "object" && payload.since !== null) {
const raw = payload.since as Record<string, unknown>;
if (
typeof raw.sessionId === "string" &&
typeof raw.epoch === "string" &&
typeof raw.seq === "number"
) {
since = { sessionId: raw.sessionId, epoch: raw.epoch, seq: raw.seq };
sessionIds.push(raw.sessionId);
}
}
if (!workspaceId && sessionIds.length === 0) {
sendError(state, ERROR_CODES.BAD_REQUEST, "subscribe requires workspaceId or sessionIds");
return;
}
for (const sessionId of new Set(sessionIds)) {
await subscribeSession(state, sessionId, workspaceHint, since?.sessionId === sessionId ? since : undefined);
}
};
const unsubscribe = (state: ClientState, payload: Record<string, unknown>): void => {
const workspaceId = typeof payload.workspaceId === "string" ? payload.workspaceId : undefined;
if (workspaceId) state.workspaceIds.delete(workspaceId);
const sessionIds = Array.isArray(payload.sessionIds)
? payload.sessionIds.filter((value): value is string => typeof value === "string")
: [];
if (typeof payload.sessionId === "string") sessionIds.push(payload.sessionId);
for (const sessionId of sessionIds) releaseSession(state, sessionId);
};
const handleMessage = async (state: ClientState, raw: RawData): Promise<void> => {
state.alive = true;
let message: Record<string, unknown>;
try {
message = JSON.parse(raw.toString()) as Record<string, unknown>;
} catch {
sendError(state, ERROR_CODES.BAD_REQUEST, "malformed JSON");
state.ws.close(CLOSE_BAD_MESSAGE, "malformed JSON");
return;
}
const type = typeof message.type === "string" ? message.type : "";
if (!state.authenticated) {
if (type !== "auth" || typeof message.token !== "string") {
sendError(state, ERROR_CODES.UNAUTHORIZED, "authenticate first");
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
return;
}
if (!authenticate(state, message.token)) {
sendError(state, ERROR_CODES.UNAUTHORIZED, "invalid device token");
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
}
return;
}
switch (type) {
case "ping":
send(state, { v: 1, type: "pong", ts: now() });
return;
case "auth":
return;
case "subscribe": {
const payload =
typeof message.payload === "object" && message.payload !== null
? (message.payload as Record<string, unknown>)
: {};
try {
await subscribe(state, payload);
} catch (error) {
const mapped = toErrorPayload(error);
sendError(state, mapped.body.code, mapped.body.message);
}
return;
}
case "unsubscribe": {
const payload =
typeof message.payload === "object" && message.payload !== null
? (message.payload as Record<string, unknown>)
: {};
unsubscribe(state, payload);
return;
}
default:
sendError(state, ERROR_CODES.BAD_REQUEST, `unknown message type "${type}"`);
}
};
const onUpgrade = (request: import("node:http").IncomingMessage, socket: Duplex, head: Buffer): void => {
if (closed) {
socket.destroy();
return;
}
const origin = typeof request.headers.origin === "string" ? request.headers.origin : undefined;
if (!isAllowedOrigin(origin, config.corsOrigins)) {
writeUpgradeRejection(socket, 403, ERROR_CODES.FORBIDDEN, "origin is not allowed");
return;
}
let pathname: string;
try {
pathname = new URL(request.url ?? "/", "http://localhost").pathname;
} catch {
writeUpgradeRejection(socket, 400, ERROR_CODES.BAD_REQUEST, "malformed URL");
return;
}
if (pathname !== "/ws" && pathname !== "/ws/") {
writeUpgradeRejection(socket, 404, ERROR_CODES.NOT_FOUND, "unknown upgrade path");
return;
}
if (clients.size >= maxConnections) {
writeUpgradeRejection(socket, 503, ERROR_CODES.RATE_LIMITED, "too many connections");
return;
}
const headerToken = bearerToken(request.headers.authorization);
if (request.headers.authorization !== undefined && headerToken === undefined) {
writeUpgradeRejection(socket, 401, ERROR_CODES.UNAUTHORIZED, "authorization must be a bearer token");
return;
}
let device: DevicePublic | null = null;
if (headerToken !== undefined) {
device = auth.verifyToken(headerToken);
if (!device) {
writeUpgradeRejection(socket, 401, ERROR_CODES.UNAUTHORIZED, "invalid device token");
return;
}
}
wss.handleUpgrade(request, socket, head, (ws) => {
const state: ClientState = {
ws,
device,
authenticated: device !== null,
workspaceIds: new Set(),
sessionWorkspaces: new Map(),
alive: true,
dropped: false,
authTimer: undefined,
};
clients.add(state);
if (device) {
auth.touchDevice(device.id);
hello(state);
} else {
state.authTimer = setTimeout(() => {
if (!state.authenticated) {
sendError(state, ERROR_CODES.UNAUTHORIZED, "authentication timeout");
state.ws.close(CLOSE_UNAUTHORIZED, "unauthorized");
}
}, authTimeoutMs);
state.authTimer.unref?.();
}
ws.on("message", (data) => {
void handleMessage(state, data);
});
ws.on("pong", () => {
state.alive = true;
});
ws.on("close", () => {
if (state.authTimer) clearTimeout(state.authTimer);
state.authTimer = undefined;
for (const sessionId of [...state.sessionWorkspaces.keys()]) {
releaseSession(state, sessionId);
}
clients.delete(state);
});
ws.on("error", (error) => {
logger?.debug("ws connection error", { error: error.message });
});
});
};
server.on("upgrade", onUpgrade);
const unsubscribeBus = bus.subscribe((record) => {
const type = typeof record.type === "string" ? record.type : "";
if (!SERVER_TYPES.has(type)) return;
const sessionId = typeof record.sessionId === "string" ? record.sessionId : undefined;
const workspaceId =
typeof record.workspaceId === "string"
? record.workspaceId
: sessionId === undefined
? undefined
: instances.findWorkspaceBySession(sessionId);
for (const state of clients) {
if (!state.authenticated) continue;
const sessionMatch = sessionId !== undefined && state.sessionWorkspaces.has(sessionId);
const workspaceMatch = workspaceId !== undefined && state.workspaceIds.has(workspaceId);
if (sessionMatch || workspaceMatch) sendEvent(state, record);
}
});
const heartbeat = setInterval(() => {
for (const state of clients) {
if (!state.alive) {
state.ws.terminate();
continue;
}
state.alive = false;
try {
state.ws.ping();
} catch {
state.ws.terminate();
}
}
}, heartbeatMs);
heartbeat.unref?.();
const close = async (): Promise<void> => {
if (closed) return;
closed = true;
server.off("upgrade", onUpgrade);
unsubscribeBus();
clearInterval(heartbeat);
for (const state of clients) {
if (state.authTimer) clearTimeout(state.authTimer);
state.ws.terminate();
}
clients.clear();
await new Promise<void>((resolve) => {
wss.close(() => resolve());
});
};
return {
wss,
connections: () => clients.size,
eventsSent: () => eventsSent,
close,
};
}
+150
View File
@@ -0,0 +1,150 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { AuthStore, hashToken, isAllowedOrigin, timingSafeEqualHex } from "../../src/daemon/auth.js";
import { DaemonError } from "../../src/daemon/errors.js";
describe("auth device store", () => {
let dir: string;
let path: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "pi2-auth-"));
path = join(dir, "devices.json");
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
it("creates a device, persists its hash and never leaks it", () => {
const auth = new AuthStore({ path });
const { token, device } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read", "steer"] });
expect(token.length).toBeGreaterThanOrEqual(40);
expect(device.id).toMatch(/^dev-/);
expect(device.name).toBe("Pixel");
expect(device.kind).toBe("phone");
expect(device.scopes).toEqual(["read", "steer"]);
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
const persisted = JSON.parse(readFileSync(path, "utf8")) as {
devices: { tokenHash: string; name: string }[];
};
expect(persisted.devices).toHaveLength(1);
expect(persisted.devices[0]!.tokenHash).toBe(hashToken(token));
expect(persisted.devices[0]!.tokenHash).toMatch(/^[0-9a-f]{64}$/);
expect(statSync(path).mode & 0o777).toBe(0o600);
const verified = auth.verifyToken(token);
expect(verified).not.toBeNull();
expect(verified!.id).toBe(device.id);
expect((verified as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
});
it("rejects unknown and tampered tokens", () => {
const auth = new AuthStore({ path });
const { token } = auth.createDevice({ name: "Laptop", kind: "laptop" });
expect(auth.verifyToken("")).toBeNull();
expect(auth.verifyToken("not-a-token")).toBeNull();
expect(auth.verifyToken(token.slice(0, -1) + (token.endsWith("A") ? "B" : "A"))).toBeNull();
});
it("persists devices across store reloads", () => {
const first = new AuthStore({ path });
const { token } = first.createDevice({ name: "Tablet", kind: "tablet" });
const second = new AuthStore({ path });
expect(second.verifyToken(token)?.name).toBe("Tablet");
expect(second.listDevices()).toHaveLength(1);
});
it("revokes devices", () => {
const auth = new AuthStore({ path });
const { token, device } = auth.createDevice({ name: "Phone", kind: "phone" });
expect(auth.revokeDevice(device.id)).toBe(true);
expect(auth.verifyToken(token)).toBeNull();
expect(auth.listDevices()[0]!.revokedAt).toBeTypeOf("number");
expect(auth.revokeDevice(device.id)).toBe(false);
expect(auth.revokeDevice("dev-unknown")).toBe(false);
const reloaded = new AuthStore({ path });
expect(reloaded.verifyToken(token)).toBeNull();
});
it("throttles touchDevice to 60 seconds", () => {
let now = 1_000_000;
const auth = new AuthStore({ path, now: () => now });
const { device } = auth.createDevice({ name: "Phone", kind: "phone" });
expect(device.lastSeenAt).toBe(now);
now += 10_000;
auth.touchDevice(device.id);
expect(auth.listDevices()[0]!.lastSeenAt).toBe(1_000_000);
now += 51_000;
auth.touchDevice(device.id);
expect(auth.listDevices()[0]!.lastSeenAt).toBe(1_061_000);
now += 1_000;
auth.touchDevice(device.id);
expect(auth.listDevices()[0]!.lastSeenAt).toBe(1_061_000);
});
it("redeems a pairing code exactly once", () => {
let now = 1_700_000_000_000;
const auth = new AuthStore({ path, now: () => now, baseUrl: "http://127.0.0.1:7676" });
const pair = auth.pairCreate({ ttlSec: 600 });
expect(pair.code).toMatch(/^[A-Z0-9]{8}$/);
expect(pair.nonce).toMatch(/^[0-9a-f]+$/);
expect(pair.url).toContain(pair.code);
expect(pair.expiresAt).toBe(now + 600_000);
const redeemed = auth.pairRedeem({ code: pair.code, deviceName: "Pixel", kind: "phone" });
expect(redeemed.device.name).toBe("Pixel");
expect(redeemed.device.kind).toBe("phone");
expect(auth.verifyToken(redeemed.token)?.id).toBe(redeemed.device.id);
expect(() => auth.pairRedeem({ code: pair.code, deviceName: "Again", kind: "laptop" })).toThrow(DaemonError);
expect(() => auth.pairRedeem({ code: "NOPE1234", deviceName: "Again", kind: "laptop" })).toThrow(/invalid|expired|used/i);
});
it("expires pairing codes", () => {
let now = 1_700_000_000_000;
const auth = new AuthStore({ path, now: () => now });
const pair = auth.pairCreate({ ttlSec: 1 });
now += 1_001;
expect(() => auth.pairRedeem({ code: pair.code, deviceName: "Pixel", kind: "phone" })).toThrow(/expired/i);
});
it("compares token hashes in constant time", () => {
const a = hashToken("token-a");
expect(timingSafeEqualHex(a, a)).toBe(true);
expect(timingSafeEqualHex(a, hashToken("token-b"))).toBe(false);
expect(timingSafeEqualHex(a, a.slice(0, 10))).toBe(false);
expect(timingSafeEqualHex("", "")).toBe(true);
});
});
describe("isAllowedOrigin", () => {
const allow = ["http://127.0.0.1:7676", "http://localhost:7676"];
it("permits non-browser requests", () => {
expect(isAllowedOrigin(undefined, allow)).toBe(true);
expect(isAllowedOrigin("", allow)).toBe(true);
});
it("permits allow-listed origins (including a trailing slash)", () => {
expect(isAllowedOrigin("http://127.0.0.1:7676", allow)).toBe(true);
expect(isAllowedOrigin("http://127.0.0.1:7676/", allow)).toBe(true);
expect(isAllowedOrigin("http://localhost:7676", allow)).toBe(true);
});
it("rejects unknown origins, schemes and ports", () => {
expect(isAllowedOrigin("http://evil.test", allow)).toBe(false);
expect(isAllowedOrigin("https://127.0.0.1:7676", allow)).toBe(false);
expect(isAllowedOrigin("http://127.0.0.1:9999", allow)).toBe(false);
expect(isAllowedOrigin("http://localhost:7676", [])).toBe(false);
});
});
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../../src/config.js";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
describe("loadConfig", () => {
it("uses protocol defaults", () => {
const config = loadConfig({});
expect(config.host).toBe("127.0.0.1");
expect(config.port).toBe(7676);
expect(config.staticDir).toBe(join(repoRoot, "web", "dist"));
expect(config.corsOrigins).toEqual(["http://127.0.0.1:7676", "http://localhost:7676"]);
expect(config.limits.maxBodyBytes).toBe(8 * 1024 * 1024);
expect(config.limits.maxFrameBytes).toBe(8 * 1024 * 1024);
expect(config.limits.maxConnections).toBe(64);
expect(config.tokenPath).toMatch(/d\.sock\.token$/);
expect(config.deviceStorePath).toMatch(/devices\.json$/);
});
it("honours environment overrides", () => {
const config = loadConfig({
PI2_PORT: "0",
PI2_HOST: "0.0.0.0",
PI2_STATIC_DIR: "/srv/pi2/web",
PI2_ORIGINS: "http://a.test, http://b.test ,,",
});
expect(config.port).toBe(0);
expect(config.host).toBe("0.0.0.0");
expect(config.staticDir).toBe("/srv/pi2/web");
expect(config.corsOrigins).toEqual(["http://a.test", "http://b.test"]);
});
it("rejects invalid ports", () => {
expect(() => loadConfig({ PI2_PORT: "-1" })).toThrow(/PI2_PORT/);
expect(() => loadConfig({ PI2_PORT: "abc" })).toThrow(/PI2_PORT/);
expect(() => loadConfig({ PI2_PORT: "70000" })).toThrow(/PI2_PORT/);
});
it("derives default origins from the port", () => {
const config = loadConfig({ PI2_PORT: "8080" });
expect(config.corsOrigins).toEqual(["http://127.0.0.1:8080", "http://localhost:8080"]);
});
});
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { DaemonError, isRetryableCode, statusForCode, toErrorPayload } from "../../src/daemon/errors.js";
import { ERROR_CODES } from "../../src/protocol/errors.js";
describe("protocol error mapping", () => {
const expected: [string, number][] = [
[ERROR_CODES.BAD_REQUEST, 400],
[ERROR_CODES.UNAUTHORIZED, 401],
[ERROR_CODES.FORBIDDEN, 403],
[ERROR_CODES.NOT_FOUND, 404],
[ERROR_CODES.METHOD_NOT_ALLOWED, 405],
[ERROR_CODES.PROTOCOL_VERSION, 426],
[ERROR_CODES.PAYLOAD_TOO_LARGE, 413],
[ERROR_CODES.RATE_LIMITED, 429],
[ERROR_CODES.INSTANCE_STARTING, 409],
[ERROR_CODES.INSTANCE_UNMANAGED, 409],
[ERROR_CODES.INSTANCE_UNAVAILABLE, 503],
[ERROR_CODES.LEASE_CONFLICT, 409],
[ERROR_CODES.EXTERNAL_SESSION, 409],
[ERROR_CODES.SESSION_NOT_FOUND, 404],
[ERROR_CODES.ATTENTION_RESOLVED, 409],
[ERROR_CODES.UNSUPPORTED, 501],
[ERROR_CODES.INTERNAL, 500],
];
it("maps every stable code to the documented HTTP status", () => {
for (const [code, status] of expected) expect(statusForCode(code)).toBe(status);
expect(statusForCode("E_WHATEVER")).toBe(500);
});
it("marks only instance-starting/unavailable as retryable", () => {
expect(isRetryableCode(ERROR_CODES.INSTANCE_STARTING)).toBe(true);
expect(isRetryableCode(ERROR_CODES.INSTANCE_UNAVAILABLE)).toBe(true);
expect(isRetryableCode(ERROR_CODES.LEASE_CONFLICT)).toBe(false);
expect(isRetryableCode(ERROR_CODES.BAD_REQUEST)).toBe(false);
});
it("wraps unknown thrown values as internal errors", () => {
const mapped = toErrorPayload(new Error("boom"));
expect(mapped.status).toBe(500);
expect(mapped.body).toMatchObject({ code: ERROR_CODES.INTERNAL, retryable: false, message: "boom" });
const forbidden = new DaemonError(ERROR_CODES.FORBIDDEN, "nope", { details: { origin: "x" } });
expect(toErrorPayload(forbidden).body).toMatchObject({ code: ERROR_CODES.FORBIDDEN, details: { origin: "x" } });
});
});
+278
View File
@@ -0,0 +1,278 @@
/**
* Deterministic fakes for the daemon surface tests.
*
* W2/W3 will provide the real `InstanceManager` / `WorkspaceStore`; the daemon
* only depends on `src/core/interfaces.ts`, so these fakes mirror those shapes.
*/
import type {
Bus,
InstanceManager,
InstanceResourcesSnapshot,
PluginConnection,
WorkspaceStore,
} from "../../src/core/interfaces.js";
import type { InstanceState, SessionState, WorkspaceInfo } from "../../src/protocol/types.js";
export interface CommandCall {
id: string;
sessionId?: string;
method: string;
params?: Record<string, unknown>;
clientRequestId?: string;
}
let deviceCounter = 0;
export class FakeConnection implements PluginConnection {
readonly instanceId: string;
readonly workspaceId: string;
readonly cwd: string;
readonly pid = process.pid;
readonly hasUI = true;
readonly listenAddr: string | null = null;
readonly pluginVersion = "test-1.0.0";
subscribed = new Set<string>();
snapshots = new Map<string, SessionState>();
seqs = new Map<string, number>();
commands: CommandCall[] = [];
sendRecords: Record<string, unknown>[] = [];
closedReason: string | undefined;
commandHandler: ((call: CommandCall) => Promise<{ seq?: number; disposition?: string }>) | undefined;
private commandCounter = 0;
constructor(workspaceId: string, instanceId = `i-${++deviceCounter}`) {
this.workspaceId = workspaceId;
this.instanceId = instanceId;
this.cwd = `/repo/${workspaceId}`;
}
send(record: Record<string, unknown>): void {
this.sendRecords.push(record);
}
async command(call: CommandCall): Promise<{ seq?: number; disposition?: string }> {
this.commands.push(call);
if (this.commandHandler) return this.commandHandler(call);
return { seq: ++this.commandCounter, disposition: "started" };
}
subscribe(sessionId: string): void {
this.subscribed.add(sessionId);
}
unsubscribe(sessionId: string): void {
this.subscribed.delete(sessionId);
}
snapshot(sessionId: string): SessionState | undefined {
return this.snapshots.get(sessionId);
}
lastSeq(sessionId: string): number {
return this.seqs.get(sessionId) ?? 0;
}
close(reason: string): void {
this.closedReason = reason;
}
}
export function makeSessionState(sessionId: string, workspaceId: string): SessionState {
return {
sessionId,
workspaceId,
cwd: `/repo/${workspaceId}`,
name: `Session ${sessionId}`,
status: "idle",
flags: { attention: false, done: true, error: false },
model: { provider: "anthropic", id: "claude-sonnet-4-5" },
thinking: "medium",
usage: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0, cost: 0.01 },
contextUsage: null,
queue: [],
todos: [],
tasks: [],
batches: [],
subagents: [],
attention: [],
entries: [],
};
}
export function makeInstanceState(workspaceId: string, instanceId: string): InstanceState {
return {
workspaceId,
instanceId,
status: "ready",
nvimPid: 1234,
pluginVersion: "test-1.0.0",
hasUI: true,
attachedClients: 0,
listenAddr: null,
startedAt: Date.now(),
};
}
export class FakeInstanceManager implements InstanceManager {
readonly instances = new Map<string, FakeConnection>();
readonly states = new Map<string, InstanceState>();
readonly sessionOwners = new Map<string, string>();
ensureCalls: string[] = [];
shutdownCalls: { workspaceId: string; mode: "drain" | "stop" }[] = [];
maybeUnsubscribeCalls: { workspaceId: string; sessionId: string }[] = [];
resourcesValue: InstanceResourcesSnapshot = {
instances: [],
totalRssBytes: 0,
physicalMemoryBytes: 16 * 1024 ** 3,
warn: false,
};
private changeHandlers: ((state: InstanceState) => void)[] = [];
addWorkspace(workspaceId: string, instanceId = `i-${workspaceId}`): FakeConnection {
const conn = new FakeConnection(workspaceId, instanceId);
this.instances.set(workspaceId, conn);
this.states.set(workspaceId, makeInstanceState(workspaceId, instanceId));
return conn;
}
async ensure(workspaceId: string): Promise<InstanceState> {
this.ensureCalls.push(workspaceId);
let state = this.states.get(workspaceId);
if (!state) {
const conn = this.addWorkspace(workspaceId);
state = this.states.get(workspaceId)!;
for (const handler of this.changeHandlers) handler(state);
void conn;
}
return state;
}
async shutdown(workspaceId: string, mode: "drain" | "stop"): Promise<void> {
this.shutdownCalls.push({ workspaceId, mode });
this.instances.delete(workspaceId);
this.states.delete(workspaceId);
}
get(workspaceId: string): PluginConnection | undefined {
return this.instances.get(workspaceId);
}
list(): InstanceState[] {
return [...this.states.values()];
}
instanceStates(): InstanceState[] {
return this.list();
}
findWorkspaceBySession(sessionId: string): string | undefined {
for (const conn of this.instances.values()) {
if (conn.subscribed.has(sessionId)) return conn.workspaceId;
}
return this.sessionOwners.get(sessionId);
}
async resources(): Promise<InstanceResourcesSnapshot> {
return this.resourcesValue;
}
maybeUnsubscribe(workspaceId: string, sessionId: string): void {
this.maybeUnsubscribeCalls.push({ workspaceId, sessionId });
}
onInstanceChange(handler: (state: InstanceState) => void): void {
this.changeHandlers.push(handler);
}
}
export function makeWorkspaceInfo(workspaceId: string, overrides: Partial<WorkspaceInfo> = {}): WorkspaceInfo {
return {
workspaceId,
cwd: `/repo/${workspaceId}`,
name: `Workspace ${workspaceId}`,
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: null,
instance: null,
...overrides,
};
}
export class FakeWorkspaceStore implements WorkspaceStore {
readonly workspaces = new Map<string, WorkspaceInfo>();
addCalls: { cwd: string; alias?: string; trust?: boolean }[] = [];
updateCalls: { workspaceId: string; patch: Record<string, unknown> }[] = [];
removeCalls: string[] = [];
refreshCalls: (string | undefined)[] = [];
constructor(seed: WorkspaceInfo[] = []) {
for (const workspace of seed) this.workspaces.set(workspace.workspaceId, workspace);
}
list(): WorkspaceInfo[] {
return [...this.workspaces.values()];
}
get(workspaceId: string): WorkspaceInfo | undefined {
return this.workspaces.get(workspaceId);
}
byCwd(cwd: string): WorkspaceInfo | undefined {
return this.list().find((workspace) => workspace.cwd === cwd);
}
async add(input: { cwd: string; alias?: string; trust?: boolean }): Promise<WorkspaceInfo> {
this.addCalls.push(input);
const workspace = makeWorkspaceInfo(`ws-${this.workspaces.size + 1}`, {
cwd: input.cwd,
alias: input.alias ?? null,
trusted: input.trust ?? false,
});
this.workspaces.set(workspace.workspaceId, workspace);
return workspace;
}
async update(
workspaceId: string,
patch: Partial<{ alias: string | null; pinned: boolean; hidden: boolean; trusted: boolean }>,
): Promise<WorkspaceInfo> {
this.updateCalls.push({ workspaceId, patch });
const current = this.workspaces.get(workspaceId) ?? makeWorkspaceInfo(workspaceId);
const next = { ...current, ...patch };
this.workspaces.set(workspaceId, next);
return next;
}
async remove(workspaceId: string): Promise<void> {
this.removeCalls.push(workspaceId);
this.workspaces.delete(workspaceId);
}
async refresh(workspaceId?: string): Promise<void> {
this.refreshCalls.push(workspaceId);
}
async ensureForCwd(cwd: string): Promise<WorkspaceInfo> {
return this.byCwd(cwd) ?? this.add({ cwd });
}
}
export class FakeBus implements Bus {
readonly published: Record<string, unknown>[] = [];
readonly handlers = new Set<(record: Record<string, unknown>) => void>();
publish(record: Record<string, unknown>): void {
this.published.push(record);
for (const handler of this.handlers) handler(record);
}
subscribe(handler: (record: Record<string, unknown>) => void): () => void {
this.handlers.add(handler);
return () => {
this.handlers.delete(handler);
};
}
}
+119
View File
@@ -0,0 +1,119 @@
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { AuthStore } from "../../src/daemon/auth.js";
import { startServer, type StartedServer } from "../../src/daemon/server.js";
import type { Config, Limits } from "../../src/config.js";
import type { WorkspaceInfo } from "../../src/protocol/types.js";
import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "./fakes.js";
export const TEST_LIMITS: Limits = {
maxBodyBytes: 8 * 1024 * 1024,
maxFrameBytes: 8 * 1024 * 1024,
maxConnections: 64,
};
export function tempDir(prefix = "pi2d-test-"): string {
return mkdtempSync(join(tmpdir(), prefix));
}
export function testConfig(overrides: Partial<Config> = {}): Config {
const base: Config = {
host: "127.0.0.1",
port: 0,
staticDir: "/nonexistent-web-dist",
corsOrigins: [],
limits: TEST_LIMITS,
tokenPath: "/tmp/pi2d-test.sock.token",
deviceStorePath: "/tmp/pi2d-test-devices.json",
};
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
}
export interface HarnessOptions {
workspaces?: WorkspaceInfo[];
seedInstances?: string[];
config?: Partial<Config>;
staticFiles?: Record<string, string>;
heartbeatMs?: number;
wsOverrides?: {
maxBufferedBytes?: number;
closeBufferedBytes?: number;
measureBufferedAmount?: (socket: unknown) => number;
};
}
export interface Harness {
dir: string;
staticDir: string;
config: Config;
auth: AuthStore;
instances: FakeInstanceManager;
workspaces: FakeWorkspaceStore;
bus: FakeBus;
server: StartedServer;
url: string;
wsUrl: string;
createToken(name?: string): string;
cleanup(): Promise<void>;
}
export async function createHarness(options: HarnessOptions = {}): Promise<Harness> {
const dir = tempDir();
const staticDir = join(dir, "web");
mkdirSync(join(staticDir, "assets"), { recursive: true });
const files: Record<string, string> = {
"index.html": "<!doctype html><title>pi2</title><div id=app></div>",
"assets/app-abc123.js": "console.log('pi2');",
...(options.staticFiles ?? {}),
};
for (const [relative, content] of Object.entries(files)) {
const target = join(staticDir, relative);
mkdirSync(join(target, ".."), { recursive: true });
writeFileSync(target, content);
}
const auth = new AuthStore({ path: join(dir, "devices.json"), baseUrl: "http://127.0.0.1:0" });
const instances = new FakeInstanceManager();
for (const workspaceId of options.seedInstances ?? []) instances.addWorkspace(workspaceId);
const workspaces = new FakeWorkspaceStore(options.workspaces ?? []);
const bus = new FakeBus();
const config = testConfig({
staticDir,
deviceStorePath: auth.path,
...options.config,
...(options.config?.limits ? { limits: { ...TEST_LIMITS, ...options.config.limits } } : {}),
});
const server = await startServer(config, {
auth,
instances,
workspaces,
bus,
daemonId: "d-test",
machineId: "m-test",
startedAt: Date.now(),
heartbeatMs: options.heartbeatMs,
ws: options.wsOverrides,
});
return {
dir,
staticDir,
config,
auth,
instances,
workspaces,
bus,
server,
url: server.url,
wsUrl: `${server.url.replace(/^http/, "ws")}/ws`,
createToken(name = "test laptop"): string {
return auth.createDevice({ name, kind: "laptop" }).token;
},
async cleanup(): Promise<void> {
await server.close();
rmSync(dir, { recursive: true, force: true });
},
};
}
+273
View File
@@ -0,0 +1,273 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
import { createHarness, TEST_LIMITS, type Harness } from "./harness.js";
import { DaemonError } from "../../src/daemon/errors.js";
import { ERROR_CODES } from "../../src/protocol/errors.js";
describe("HTTP API", () => {
let h: Harness;
let token: string;
let conn: NonNullable<ReturnType<Harness["instances"]["get"]>>;
beforeEach(async () => {
h = await createHarness({
workspaces: [makeWorkspaceInfo("ws-1")],
seedInstances: ["ws-1"],
config: { corsOrigins: ["http://allowed.test"] },
});
token = h.createToken();
h.instances.sessionOwners.set("s1", "ws-1");
conn = h.instances.get("ws-1")!;
conn.snapshots.set("s1", makeSessionState("s1", "ws-1"));
conn.seqs.set("s1", 7);
});
afterEach(async () => {
await h.cleanup();
});
function authed(init: RequestInit = {}): RequestInit {
return {
...init,
headers: { Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },
};
}
it("serves info and health without auth on loopback", async () => {
const info = await fetch(`${h.url}/api/v1/info`);
expect(info.status).toBe(200);
const body = (await info.json()) as Record<string, unknown>;
expect(body.v).toBe(1);
expect(body.daemonId).toBe("d-test");
expect(body.machineId).toBe("m-test");
expect(body.limits).toEqual(TEST_LIMITS);
const health = await fetch(`${h.url}/api/v1/health`);
expect(health.status).toBe(200);
const healthBody = (await health.json()) as { ok: boolean; items: { name: string; ok: boolean }[] };
expect(healthBody.ok).toBe(true);
expect(healthBody.items.length).toBeGreaterThan(0);
expect(healthBody.items.every((item) => item.ok)).toBe(true);
});
it("requires a bearer token for all other API reads", async () => {
const anonymous = await fetch(`${h.url}/api/v1/workspaces`);
expect(anonymous.status).toBe(401);
expect(((await anonymous.json()) as { code: string }).code).toBe(ERROR_CODES.UNAUTHORIZED);
const bad = await fetch(`${h.url}/api/v1/workspaces`, {
headers: { Authorization: "Bearer nope" },
});
expect(bad.status).toBe(401);
const good = await fetch(`${h.url}/api/v1/workspaces`, authed());
expect(good.status).toBe(200);
const workspaces = (await good.json()) as { workspaceId: string }[];
expect(workspaces.map((workspace) => workspace.workspaceId)).toEqual(["ws-1"]);
});
it("enforces the origin allow-list on open and authenticated endpoints", async () => {
const denied = await fetch(`${h.url}/api/v1/info`, {
headers: { Origin: "http://evil.test" },
});
expect(denied.status).toBe(403);
expect(((await denied.json()) as { code: string }).code).toBe(ERROR_CODES.FORBIDDEN);
const allowed = await fetch(`${h.url}/api/v1/info`, {
headers: { Origin: "http://allowed.test" },
});
expect(allowed.status).toBe(200);
expect(allowed.headers.get("access-control-allow-origin")).toBe("http://allowed.test");
const allowedWithToken = await fetch(
`${h.url}/api/v1/workspaces`,
authed({ headers: { Origin: "http://allowed.test" } }),
);
expect(allowedWithToken.status).toBe(200);
expect(allowedWithToken.headers.get("access-control-allow-origin")).toBe("http://allowed.test");
});
it("answers CORS preflight", async () => {
const res = await fetch(`${h.url}/api/v1/cmd`, {
method: "OPTIONS",
headers: {
Origin: "http://allowed.test",
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "authorization,content-type",
},
});
expect(res.status).toBe(204);
expect(res.headers.get("access-control-allow-origin")).toBe("http://allowed.test");
expect(res.headers.get("access-control-allow-methods")).toContain("POST");
expect(res.headers.get("access-control-allow-headers")?.toLowerCase()).toContain("authorization");
const denied = await fetch(`${h.url}/api/v1/cmd`, {
method: "OPTIONS",
headers: { Origin: "http://evil.test" },
});
expect(denied.status).toBe(403);
});
it("routes commands to the owning instance and dedupes clientRequestId", async () => {
const payload = {
method: "prompt.send",
sessionId: "s1",
params: { text: "hi" },
clientRequestId: "c-1",
};
const first = await fetch(`${h.url}/api/v1/cmd`, authed({ method: "POST", body: JSON.stringify(payload) }));
expect(first.status).toBe(202);
const firstBody = (await first.json()) as Record<string, unknown>;
expect(firstBody.accepted).toBe(true);
expect(firstBody.disposition).toBe("started");
const second = await fetch(`${h.url}/api/v1/cmd`, authed({ method: "POST", body: JSON.stringify(payload) }));
expect(second.status).toBe(202);
expect(await second.json()).toEqual(firstBody);
expect(h.instances.ensureCalls).toEqual(["ws-1"]);
expect(conn.commands).toHaveLength(1);
expect(conn.commands[0]!.method).toBe("prompt.send");
expect(conn.commands[0]!.clientRequestId).toBe("c-1");
});
it("rejects malformed JSON and unknown sessions", async () => {
const malformed = await fetch(`${h.url}/api/v1/cmd`, authed({ method: "POST", body: "{not json" }));
expect(malformed.status).toBe(400);
expect(((await malformed.json()) as { code: string }).code).toBe(ERROR_CODES.BAD_REQUEST);
const missing = await fetch(
`${h.url}/api/v1/cmd`,
authed({ method: "POST", body: JSON.stringify({ method: "prompt.send", sessionId: "missing" }) }),
);
expect(missing.status).toBe(404);
expect(((await missing.json()) as { code: string }).code).toBe(ERROR_CODES.SESSION_NOT_FOUND);
});
it("maps router errors to HTTP statuses", async () => {
conn.commandHandler = async () => {
throw new DaemonError(ERROR_CODES.LEASE_CONFLICT, "session is owned by instance i-2");
};
const res = await fetch(
`${h.url}/api/v1/cmd`,
authed({ method: "POST", body: JSON.stringify({ method: "prompt.send", sessionId: "s1" }) }),
);
expect(res.status).toBe(409);
const body = (await res.json()) as { code: string; retryable: boolean };
expect(body.code).toBe(ERROR_CODES.LEASE_CONFLICT);
expect(body.retryable).toBe(false);
});
it("enforces the body limit", async () => {
const small = await createHarness({ config: { limits: { ...TEST_LIMITS, maxBodyBytes: 16 } } });
try {
const localToken = small.createToken();
const res = await fetch(`${small.url}/api/v1/cmd`, {
method: "POST",
headers: { Authorization: `Bearer ${localToken}` },
body: JSON.stringify({ method: "prompt.send", params: { text: "far too much text" } }),
});
expect(res.status).toBe(413);
expect(((await res.json()) as { code: string }).code).toBe(ERROR_CODES.PAYLOAD_TOO_LARGE);
} finally {
await small.cleanup();
}
});
it("relays workspace/session queries through instance.command", async () => {
conn.commandHandler = async (call) => {
if (call.method === "workspace.query" && call.params?.kind === "sessions") {
return { seq: 1, disposition: "started", sessions: [{ sessionId: "s1" }] } as never;
}
if (call.method === "session.entries") {
return { seq: 1, disposition: "started", entries: [{ id: "e1" }] } as never;
}
return { seq: 1, disposition: "started" };
};
const sessions = await fetch(`${h.url}/api/v1/workspaces/ws-1/sessions`, authed());
expect(sessions.status).toBe(200);
const sessionsBody = (await sessions.json()) as { sessions: { sessionId: string }[] };
expect(sessionsBody.sessions).toEqual([{ sessionId: "s1" }]);
const entries = await fetch(`${h.url}/api/v1/sessions/s1/entries?before=e9&limit=25`, authed());
expect(entries.status).toBe(200);
const entryCall = conn.commands.find((call) => call.method === "session.entries");
expect(entryCall?.params).toEqual({ before: "e9", limit: 25 });
expect((await entries.json()) as { entries: unknown[] }).toHaveProperty("entries");
const attention = await fetch(`${h.url}/api/v1/attention?workspaceId=ws-1`, authed());
expect(attention.status).toBe(200);
const models = await fetch(`${h.url}/api/v1/models?workspaceId=ws-1`, authed());
expect(models.status).toBe(200);
expect(conn.commands.some((call) => call.method === "workspace.query" && call.params?.kind === "models")).toBe(
true,
);
});
it("returns resources and diagnostics", async () => {
h.instances.resourcesValue = {
instances: [
{
workspaceId: "ws-1",
instanceId: "i-ws-1",
nvimPid: 42,
rssBytes: 1000,
sessions: 1,
hasUI: true,
},
],
totalRssBytes: 1000,
physicalMemoryBytes: 2000,
warn: false,
};
const resources = await fetch(`${h.url}/api/v1/resources`, authed());
expect(resources.status).toBe(200);
expect(((await resources.json()) as { totalRssBytes: number }).totalRssBytes).toBe(1000);
const diagnostics = await fetch(`${h.url}/api/v1/diagnostics`, authed());
expect(diagnostics.status).toBe(200);
const body = (await diagnostics.json()) as { instances: unknown[]; connections: number };
expect(body.instances).toHaveLength(1);
expect(body.connections).toBe(0);
});
it("lists and revokes devices", async () => {
const list = await fetch(`${h.url}/api/v1/devices`, authed());
expect(list.status).toBe(200);
const devices = (await list.json()) as { id: string; tokenHash?: string }[];
expect(devices).toHaveLength(1);
expect(devices[0]!.tokenHash).toBeUndefined();
const revoked = await fetch(`${h.url}/api/v1/devices/${devices[0]!.id}`, authed({ method: "DELETE" }));
expect(revoked.status).toBe(204);
expect(h.auth.verifyToken(token)).toBeNull();
});
it("redeems a pairing code over HTTP", async () => {
const pair = h.auth.pairCreate();
const res = await fetch(`${h.url}/api/v1/pair`, {
method: "POST",
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
});
expect(res.status).toBe(200);
const body = (await res.json()) as { token: string; device: { name: string } };
expect(body.device.name).toBe("Pixel");
expect(h.auth.verifyToken(body.token)?.name).toBe("Pixel");
const replay = await fetch(`${h.url}/api/v1/pair`, {
method: "POST",
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
});
expect(replay.status).toBe(401);
});
it("creates a pairing code for an authenticated client", async () => {
const res = await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }));
expect(res.status).toBe(200);
const body = (await res.json()) as { code: string; url: string; expiresAt: number };
expect(body.code).toMatch(/^[A-Z0-9]{8}$/);
expect(body.url).toContain(body.code);
expect(body.expiresAt).toBeGreaterThan(Date.now());
});
});
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import type { Logger, LogLevel } from "../../src/core/interfaces.js";
import { InMemoryBus } from "../../src/daemon/hub.js";
class RecordingLogger implements Logger {
records: { level: LogLevel; msg: string; fields?: Record<string, unknown> }[] = [];
debug(msg: string, fields?: Record<string, unknown>): void {
this.records.push({ level: "debug", msg, fields });
}
info(msg: string, fields?: Record<string, unknown>): void {
this.records.push({ level: "info", msg, fields });
}
warn(msg: string, fields?: Record<string, unknown>): void {
this.records.push({ level: "warn", msg, fields });
}
error(msg: string, fields?: Record<string, unknown>): void {
this.records.push({ level: "error", msg, fields });
}
child(): Logger {
return this;
}
}
describe("InMemoryBus", () => {
it("publishes to every subscriber until unsubscribed", () => {
const bus = new InMemoryBus();
const first: Record<string, unknown>[] = [];
const second: Record<string, unknown>[] = [];
const unsubscribe = bus.subscribe((record) => first.push(record));
bus.subscribe((record) => second.push(record));
bus.publish({ type: "event", sessionId: "s1" });
expect(first).toHaveLength(1);
expect(second).toHaveLength(1);
unsubscribe();
bus.publish({ type: "event", sessionId: "s2" });
expect(first).toHaveLength(1);
expect(second).toHaveLength(2);
});
it("isolates handler failures and warns", () => {
const logger = new RecordingLogger();
const bus = new InMemoryBus({ logger });
const seen: Record<string, unknown>[] = [];
bus.subscribe(() => {
throw new Error("handler exploded");
});
bus.subscribe((record) => seen.push(record));
expect(() => bus.publish({ type: "event" })).not.toThrow();
expect(seen).toHaveLength(1);
expect(logger.records.some((record) => record.level === "warn" && /handler/i.test(record.msg))).toBe(true);
});
it("warns about slow handlers", () => {
const logger = new RecordingLogger();
const bus = new InMemoryBus({ logger, slowHandlerMs: 5 });
bus.subscribe(() => {
const end = Date.now() + 20;
while (Date.now() < end) {
// busy wait to simulate a blocking handler
}
});
bus.publish({ type: "event" });
expect(logger.records.some((record) => record.level === "warn" && /slow/i.test(record.msg))).toBe(true);
});
});
+164
View File
@@ -0,0 +1,164 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { AuthStore } from "../../src/daemon/auth.js";
import { DaemonError } from "../../src/daemon/errors.js";
import { CommandRouter } from "../../src/daemon/router.js";
import { ERROR_CODES } from "../../src/protocol/errors.js";
import { FakeInstanceManager, FakeWorkspaceStore, makeWorkspaceInfo } from "./fakes.js";
describe("CommandRouter", () => {
let dir: string;
let auth: AuthStore;
let instances: FakeInstanceManager;
let workspaces: FakeWorkspaceStore;
let router: CommandRouter;
let now: number;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "pi2-router-"));
auth = new AuthStore({ path: join(dir, "devices.json") });
instances = new FakeInstanceManager();
workspaces = new FakeWorkspaceStore([makeWorkspaceInfo("ws-1")]);
instances.addWorkspace("ws-1");
instances.sessionOwners.set("s1", "ws-1");
now = 1_700_000_000_000;
router = new CommandRouter({ auth, instances, workspaces, now: () => now, daemonId: "d-test" });
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
it("dedupes clientRequestId for five minutes", async () => {
const conn = instances.get("ws-1")!;
const request = { method: "prompt.send", sessionId: "s1", clientRequestId: "c-1" };
const first = await router.dispatch(request);
expect(first.status).toBe(202);
expect(first.body.accepted).toBe(true);
expect(first.body.disposition).toBe("started");
const replay = await router.dispatch(request);
expect(replay).toEqual(first);
expect(conn.commands).toHaveLength(1);
now += 5 * 60 * 1000 - 1;
await router.dispatch(request);
expect(conn.commands).toHaveLength(1);
now += 1;
await router.dispatch(request);
expect(conn.commands).toHaveLength(2);
});
it("does not collide clientRequestIds across methods", async () => {
const conn = instances.get("ws-1")!;
await router.dispatch({ method: "prompt.send", sessionId: "s1", clientRequestId: "same" });
await router.dispatch({ method: "session.rename", sessionId: "s1", clientRequestId: "same" });
expect(conn.commands.map((call) => call.method)).toEqual(["prompt.send", "session.rename"]);
});
it("maps known and unknown errors to status and errorBody", async () => {
const conn = instances.get("ws-1")!;
conn.commandHandler = async () => {
throw new DaemonError(ERROR_CODES.LEASE_CONFLICT, "session is owned by instance i-2");
};
const lease = await router.dispatch({ method: "prompt.send", sessionId: "s1" });
expect(lease.status).toBe(409);
expect(lease.body).toMatchObject({ code: ERROR_CODES.LEASE_CONFLICT, retryable: false });
conn.commandHandler = async () => {
throw new Error("boom");
};
const internal = await router.dispatch({ method: "prompt.send", sessionId: "s1" });
expect(internal.status).toBe(500);
expect(internal.body.code).toBe(ERROR_CODES.INTERNAL);
const unavailable = new DaemonError(ERROR_CODES.INSTANCE_UNAVAILABLE, "no instance");
expect(unavailable.status).toBe(503);
expect(unavailable.retryable).toBe(true);
const missing = await router.dispatch({ method: "prompt.send", sessionId: "nope" });
expect(missing.status).toBe(404);
expect(missing.body.code).toBe(ERROR_CODES.SESSION_NOT_FOUND);
const noTarget = await router.dispatch({ method: "prompt.send" });
expect(noTarget.status).toBe(400);
expect(noTarget.body.code).toBe(ERROR_CODES.BAD_REQUEST);
});
it("routes workspace methods to the workspace store", async () => {
const added = await router.dispatch({ method: "workspace.add", params: { cwd: "/repo/new", alias: "n" } });
expect(added.status).toBe(202);
expect(workspaces.addCalls).toEqual([{ cwd: "/repo/new", alias: "n" }]);
await router.dispatch({ method: "workspace.update", params: { workspaceId: "ws-1", patch: { alias: "x" } } });
expect(workspaces.updateCalls).toEqual([{ workspaceId: "ws-1", patch: { alias: "x" } }]);
await router.dispatch({ method: "workspace.remove", params: { workspaceId: "ws-1" } });
expect(workspaces.removeCalls).toEqual(["ws-1"]);
await router.dispatch({ method: "workspace.refresh", params: { workspaceId: "ws-1" } });
expect(workspaces.refreshCalls).toEqual(["ws-1"]);
});
it("routes instance and system methods to the instance manager", async () => {
const ensured = await router.dispatch({ method: "instance.ensure", params: { workspaceId: "ws-1" } });
expect(ensured.status).toBe(202);
expect(ensured.body.instance).toMatchObject({ workspaceId: "ws-1" });
expect(instances.ensureCalls).toEqual(["ws-1"]);
await router.dispatch({ method: "instance.shutdown", params: { workspaceId: "ws-1", mode: "drain" } });
expect(instances.shutdownCalls).toEqual([{ workspaceId: "ws-1", mode: "drain" }]);
const doctor = await router.dispatch({ method: "system.doctor" });
expect(doctor.status).toBe(202);
expect(doctor.body.instances).toBeTypeOf("object");
});
it("routes pairing and device methods to auth", async () => {
const created = await router.dispatch({ method: "pair.create", params: { ttlSec: 120 } });
expect(created.status).toBe(202);
const code = created.body.code as string;
expect(code).toMatch(/^[A-Z0-9]{8}$/);
const redeemed = await router.dispatch({
method: "pair.redeem",
params: { code, deviceName: "Pixel", kind: "phone" },
});
expect(redeemed.status).toBe(202);
const token = redeemed.body.token as string;
expect(auth.verifyToken(token)?.name).toBe("Pixel");
const deviceId = (redeemed.body.device as { id: string }).id;
const revoked = await router.dispatch({ method: "device.revoke", params: { deviceId } });
expect(revoked.status).toBe(202);
expect(auth.verifyToken(token)).toBeNull();
});
it("resolves a command without sessionId from params.workspaceId", async () => {
const conn = instances.get("ws-1")!;
const result = await router.dispatch({
method: "session.create",
params: { workspaceId: "ws-1", cwd: "/repo/ws-1" },
});
expect(result.status).toBe(202);
expect(conn.commands[0]!.params).toEqual({ workspaceId: "ws-1", cwd: "/repo/ws-1" });
});
it("does not cache failed commands", async () => {
const conn = instances.get("ws-1")!;
let attempts = 0;
conn.commandHandler = async () => {
attempts += 1;
if (attempts === 1) throw new DaemonError(ERROR_CODES.INSTANCE_STARTING, "booting");
return { seq: 1, disposition: "started" };
};
const request = { method: "prompt.send", sessionId: "s1", clientRequestId: "c-retry" };
const failed = await router.dispatch(request);
expect(failed.status).toBe(409);
const retried = await router.dispatch(request);
expect(retried.status).toBe(202);
expect(attempts).toBe(2);
});
});
+85
View File
@@ -0,0 +1,85 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { makeWorkspaceInfo } from "./fakes.js";
import { createHarness, type Harness } from "./harness.js";
describe("SSE fallback", () => {
let h: Harness;
let token: string;
beforeEach(async () => {
h = await createHarness({
workspaces: [makeWorkspaceInfo("ws-1")],
seedInstances: ["ws-1"],
config: { corsOrigins: ["http://allowed.test"] },
});
token = h.createToken();
});
afterEach(async () => {
await h.cleanup();
});
async function readUntil(
reader: ReadableStreamDefaultReader<Uint8Array>,
needle: string,
timeoutMs = 2000,
): Promise<string> {
const decoder = new TextDecoder();
let text = "";
const deadline = Date.now() + timeoutMs;
while (!text.includes(needle)) {
if (Date.now() > deadline) throw new Error(`timeout waiting for ${needle}; got ${text}`);
const result = await Promise.race([
reader.read(),
new Promise<never>((_, reject) => setTimeout(() => reject(new Error("read timeout")), timeoutMs)),
]);
if (result.done) break;
text += decoder.decode(result.value, { stream: true });
}
return text;
}
it("requires a valid token and origin", async () => {
const missing = await fetch(`${h.url}/events`);
expect(missing.status).toBe(401);
const bad = await fetch(`${h.url}/events?token=nope`);
expect(bad.status).toBe(401);
const badOrigin = await fetch(`${h.url}/events?token=${token}`, {
headers: { Origin: "http://evil.test" },
});
expect(badOrigin.status).toBe(403);
});
it("streams only the requested session's events", async () => {
const controller = new AbortController();
const res = await fetch(`${h.url}/events?token=${encodeURIComponent(token)}&sessionId=s1`, {
signal: controller.signal,
headers: { Origin: "http://allowed.test" },
});
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/event-stream");
expect(res.headers.get("access-control-allow-origin")).toBe("http://allowed.test");
const reader = res.body!.getReader();
await new Promise((resolve) => setTimeout(resolve, 50));
h.bus.publish({ v: 1, type: "event", workspaceId: "ws-1", sessionId: "s2", epoch: "i-ws-1", seq: 1, payload: {} });
h.bus.publish({
v: 1,
type: "event",
workspaceId: "ws-1",
sessionId: "s1",
epoch: "i-ws-1",
seq: 2,
payload: { event: { type: "agent_start", ts: 1 } },
});
const text = await readUntil(reader, '"sessionId":"s1"');
expect(text).toContain('"sessionId":"s1"');
expect(text).not.toContain('"sessionId":"s2"');
controller.abort();
await reader.cancel().catch(() => undefined);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { createHarness, type Harness } from "./harness.js";
describe("static file surface", () => {
let h: Harness;
let token: string;
beforeEach(async () => {
h = await createHarness();
token = h.createToken();
});
afterEach(async () => {
await h.cleanup();
});
it("serves index.html with no-store", async () => {
const res = await fetch(`${h.url}/`);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/html");
expect(res.headers.get("cache-control")).toBe("no-store");
expect(await res.text()).toContain("<div id=app>");
});
it("serves hashed assets with immutable caching", async () => {
const res = await fetch(`${h.url}/assets/app-abc123.js`);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/javascript");
expect(res.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");
expect(await res.text()).toBe("console.log('pi2');");
});
it("falls back to index.html for SPA routes", async () => {
const res = await fetch(`${h.url}/sessions/s1/deep/route`);
expect(res.status).toBe(200);
expect(res.headers.get("cache-control")).toBe("no-store");
expect(await res.text()).toContain("<div id=app>");
});
it("returns 404 for a missing asset with an extension", async () => {
const res = await fetch(`${h.url}/assets/missing-deadbeef.js`);
expect(res.status).toBe(404);
expect(await res.text()).not.toContain("<div id=app>");
});
it("does not serve files outside staticDir", async () => {
writeFileSync(join(h.dir, "secret.txt"), "TOP-SECRET");
const attempts = [
`${h.url}/%2e%2e/secret.txt`,
`${h.url}/assets/%2e%2e/%2e%2e/secret.txt`,
`${h.url}/..%2F..%2Fsecret.txt`,
];
for (const url of attempts) {
const res = await fetch(url);
expect(res.status).toBe(404);
expect(await res.text()).not.toContain("TOP-SECRET");
}
});
it("never falls back to index for /api or /ws", async () => {
const api = await fetch(`${h.url}/api/v1/does-not-exist`, {
headers: { Authorization: `Bearer ${token}` },
});
expect(api.status).toBe(404);
expect(await api.text()).not.toContain("<div id=app>");
const ws = await fetch(`${h.url}/ws`);
expect(ws.status).toBe(404);
expect(await ws.text()).not.toContain("<div id=app>");
});
it("rejects missing files that look like files", async () => {
const res = await fetch(`${h.url}/missing.json`);
expect(res.status).toBe(404);
});
it("supports HEAD but rejects other methods", async () => {
const head = await fetch(`${h.url}/`, { method: "HEAD" });
expect(head.status).toBe(200);
expect(head.headers.get("content-type")).toContain("text/html");
expect(await head.text()).toBe("");
const post = await fetch(`${h.url}/`, { method: "POST" });
expect(post.status).toBe(405);
const body = (await post.json()) as { code: string };
expect(body.code).toBe("E_METHOD_NOT_ALLOWED");
});
});
+298
View File
@@ -0,0 +1,298 @@
import { once } from "node:events";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
import { makeSessionState, makeWorkspaceInfo } from "./fakes.js";
import { createHarness, type Harness } from "./harness.js";
type Record0 = Record<string, unknown> & { type?: string };
class WsClient {
readonly messages: Record0[] = [];
private waiters: {
predicate: (message: Record0) => boolean;
resolve: (message: Record0) => void;
reject: (error: Error) => void;
timer: NodeJS.Timeout;
}[] = [];
constructor(readonly ws: WebSocket) {
ws.on("message", (data) => {
const message = JSON.parse(data.toString()) as Record0;
const index = this.waiters.findIndex((waiter) => waiter.predicate(message));
if (index >= 0) {
const [waiter] = this.waiters.splice(index, 1);
clearTimeout(waiter!.timer);
waiter!.resolve(message);
return;
}
this.messages.push(message);
});
}
send(message: Record<string, unknown>): void {
this.ws.send(JSON.stringify(message));
}
next(predicate: (message: Record0) => boolean = () => true, timeoutMs = 2000): Promise<Record0> {
const index = this.messages.findIndex(predicate);
if (index >= 0) return Promise.resolve(this.messages.splice(index, 1)[0]!);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
const idx = this.waiters.findIndex((waiter) => waiter.timer === timer);
if (idx >= 0) this.waiters.splice(idx, 1);
reject(new Error(`timeout waiting for WS message; buffered=${JSON.stringify(this.messages)}`));
}, timeoutMs);
this.waiters.push({ predicate, resolve, reject, timer });
});
}
async expectSilence(ms = 200): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
expect(this.messages).toEqual([]);
}
async close(): Promise<void> {
if (this.ws.readyState === WebSocket.CLOSED) return;
this.ws.close();
await once(this.ws, "close");
}
}
function openWs(url: string, headers?: Record<string, string>): Promise<WsClient> {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url, headers ? { headers } : undefined);
const client = new WsClient(ws);
ws.once("open", () => resolve(client));
ws.once("error", reject);
ws.once("unexpected-response", (_request, response) => {
reject(Object.assign(new Error("unexpected upgrade response"), { statusCode: response.statusCode }));
});
});
}
async function authedClient(url: string, token: string): Promise<WsClient> {
const client = await openWs(url);
client.send({ type: "auth", token });
const hello = await client.next((message) => message.type === "hello_ack");
expect(hello.type).toBe("hello_ack");
return client;
}
describe("WebSocket surface", () => {
let h: Harness;
let token: string;
afterEach(async () => {
if (h) await h.cleanup();
});
async function setup(configOptions: Parameters<typeof createHarness>[0] = {}): Promise<void> {
h = await createHarness({
workspaces: [makeWorkspaceInfo("ws-1")],
seedInstances: ["ws-1"],
...configOptions,
});
token = h.createToken();
h.instances.sessionOwners.set("s1", "ws-1");
h.instances.sessionOwners.set("s2", "ws-1");
}
it("requires auth as the first message", async () => {
await setup();
const client = await openWs(h.wsUrl);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
const error = await client.next((message) => message.type === "error");
expect(error.type).toBe("error");
expect((error.payload as { code: string }).code).toBe("E_UNAUTHORIZED");
await once(client.ws, "close");
expect(client.ws.readyState).toBe(WebSocket.CLOSED);
});
it("accepts a first-message auth and returns hello_ack", async () => {
await setup();
const client = await authedClient(h.wsUrl, token);
const hello = client.messages.find((message) => message.type === "hello_ack");
expect(hello).toBeUndefined();
await client.close();
});
it("accepts a bearer token in the upgrade header", async () => {
await setup();
const client = await openWs(h.wsUrl, { Authorization: `Bearer ${token}` });
const hello = await client.next((message) => message.type === "hello_ack");
expect(hello.daemonId).toBe("d-test");
expect((hello.limits as { maxFrameBytes: number }).maxFrameBytes).toBe(8 * 1024 * 1024);
expect((hello.device as { name: string }).name).toBe("test laptop");
await client.close();
});
it("rejects an unknown origin during upgrade", async () => {
await setup();
await expect(openWs(h.wsUrl, { Origin: "http://evil.test" })).rejects.toMatchObject({ statusCode: 403 });
});
it("rejects an invalid token", async () => {
await setup();
const client = await openWs(h.wsUrl);
client.send({ type: "auth", token: "nope" });
const error = await client.next((message) => message.type === "error");
expect((error.payload as { code: string }).code).toBe("E_UNAUTHORIZED");
await once(client.ws, "close");
});
it("subscribes, ensures the instance and sends a snapshot", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
conn.snapshots.set("s1", makeSessionState("s1", "ws-1"));
conn.seqs.set("s1", 7);
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
const snapshot = await client.next((message) => message.type === "snapshot");
expect(snapshot.sessionId).toBe("s1");
expect(snapshot.epoch).toBe("i-ws-1");
expect(snapshot.seq).toBe(7);
expect((snapshot.payload as { state: { sessionId: string } }).state.sessionId).toBe("s1");
expect(h.instances.ensureCalls).toContain("ws-1");
expect(conn.subscribed.has("s1")).toBe(true);
await client.close();
});
it("sends resync_required when epoch or seq do not match", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
conn.snapshots.set("s1", makeSessionState("s1", "ws-1"));
conn.seqs.set("s1", 7);
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"], since: { sessionId: "s1", epoch: "old-epoch", seq: 7 } } });
const epochMismatch = await client.next((message) => message.type === "resync_required");
expect(epochMismatch.sessionId).toBe("s1");
client.send({ type: "subscribe", payload: { sessionIds: ["s1"], since: { sessionId: "s1", epoch: "i-ws-1", seq: 99 } } });
const seqMismatch = await client.next((message) => message.type === "resync_required");
expect(seqMismatch.sessionId).toBe("s1");
client.send({ type: "subscribe", payload: { sessionIds: ["s1"], since: { sessionId: "s1", epoch: "i-ws-1", seq: 7 } } });
const snapshot = await client.next((message) => message.type === "snapshot");
expect(snapshot.seq).toBe(7);
await client.close();
});
it("fans records out only to subscribers", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
conn.snapshots.set("s1", makeSessionState("s1", "ws-1"));
conn.snapshots.set("s2", makeSessionState("s2", "ws-1"));
const first = await authedClient(h.wsUrl, token);
first.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
await first.next((message) => message.type === "snapshot");
const second = await authedClient(h.wsUrl, token);
second.send({ type: "subscribe", payload: { sessionIds: ["s2"] } });
await second.next((message) => message.type === "snapshot");
h.bus.publish({
v: 1,
type: "event",
workspaceId: "ws-1",
sessionId: "s1",
epoch: "i-ws-1",
seq: 8,
ts: 1,
payload: { event: { type: "agent_start", ts: 1 } },
});
const event = await first.next((message) => message.type === "event");
expect(event.sessionId).toBe("s1");
await second.expectSilence();
await first.close();
await second.close();
});
it("delivers workspace-scoped records", async () => {
await setup();
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { workspaceId: "ws-1" } });
await new Promise((resolve) => setTimeout(resolve, 50));
h.bus.publish({ v: 1, type: "event", workspaceId: "ws-1", sessionId: "s9", epoch: "i-ws-1", seq: 1, payload: {} });
const event = await client.next((message) => message.type === "event");
expect(event.sessionId).toBe("s9");
await client.close();
});
it("stops delivering after unsubscribe", async () => {
await setup();
const conn = h.instances.get("ws-1")!;
conn.snapshots.set("s1", makeSessionState("s1", "ws-1"));
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
await client.next((message) => message.type === "snapshot");
client.send({ type: "unsubscribe", payload: { sessionIds: ["s1"] } });
await new Promise((resolve) => setTimeout(resolve, 50));
h.bus.publish({ v: 1, type: "event", workspaceId: "ws-1", sessionId: "s1", epoch: "i-ws-1", seq: 8, payload: {} });
await client.expectSilence();
await client.close();
});
it("drops records over the buffer cap and emits one dropped marker", async () => {
await setup({
wsOverrides: {
maxBufferedBytes: 5,
closeBufferedBytes: 1_000_000,
measureBufferedAmount: () => 10,
},
});
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
await new Promise((resolve) => setTimeout(resolve, 50));
h.bus.publish({ v: 1, type: "event", workspaceId: "ws-1", sessionId: "s1", epoch: "i-ws-1", seq: 1, payload: {} });
const dropped = await client.next((message) => message.type === "dropped");
expect(dropped.type).toBe("dropped");
h.bus.publish({ v: 1, type: "event", workspaceId: "ws-1", sessionId: "s1", epoch: "i-ws-1", seq: 2, payload: {} });
await client.expectSilence();
await client.close();
});
it("closes a socket that exceeds the hard buffer limit", async () => {
await setup({
wsOverrides: {
maxBufferedBytes: 5,
closeBufferedBytes: 100,
measureBufferedAmount: () => 200,
},
});
const client = await authedClient(h.wsUrl, token);
client.send({ type: "subscribe", payload: { sessionIds: ["s1"] } });
await new Promise((resolve) => setTimeout(resolve, 50));
h.bus.publish({ v: 1, type: "event", workspaceId: "ws-1", sessionId: "s1", epoch: "i-ws-1", seq: 1, payload: {} });
const [code] = (await once(client.ws, "close")) as [number];
expect(code).toBe(1013);
});
it("answers ping with pong", async () => {
await setup();
const client = await authedClient(h.wsUrl, token);
client.send({ type: "ping" });
const pong = await client.next((message) => message.type === "pong");
expect(pong.type).toBe("pong");
await client.close();
});
it("sends heartbeat pings", async () => {
await setup({ heartbeatMs: 25 });
const client = await authedClient(h.wsUrl, token);
await once(client.ws, "ping");
await client.close();
});
});