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

+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();
});
});