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:
1 parent
bdcab3ce29
commit
ba3719fad9
21 files changed
+3619
No files matched your search
@@ -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`,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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() };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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 });
|
||||
},
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user