@wonderwhy-er/desktop-commander
Version:
MCP server for terminal operations and file editing
275 lines (274 loc) • 13 kB
JavaScript
import { connect } from "mqtt";
import { observeTransport } from "../transport-telemetry.js";
// Ids become literal topic segments; reject separators and MQTT wildcards.
const ID = /^[A-Za-z0-9_-]{1,128}$/;
const CONNECT_TIMEOUT_MS = 10000;
/** Connect using the enrolled device identity and the system's trusted broker certificates. */
export function createMqttConfig(credentials) {
let url;
try {
url = new URL(credentials.url);
}
catch {
throw new Error("MQTT broker configuration requires a valid URL");
}
if (url.username ||
url.password ||
url.search ||
url.hash ||
(url.pathname && url.pathname !== "/")) {
throw new Error("MQTT broker URL must not contain credentials, paths, or query parameters");
}
if (url.protocol !== "mqtts:")
throw new Error("MQTT broker URL must use mqtts://");
if (!credentials.cert || !credentials.key) {
throw new Error("MQTT requires an enrolled device certificate and private key");
}
// Clean sessions avoid backlog replay; reconnects must obtain a fresh SUBACK before admission.
const options = {
protocolVersion: 4,
clean: true,
keepalive: 30,
connectTimeout: CONNECT_TIMEOUT_MS,
resubscribe: false,
queueQoSZero: false,
cert: credentials.cert,
key: credentials.key,
rejectUnauthorized: true,
};
return { url: url.toString(), options };
}
/** Match the server publisher's exact device topic without granting wildcard subscriptions. */
export function mqttDoorbellTopic(userId, deviceId) {
if (!ID.test(userId) || !ID.test(deviceId))
throw new Error("Invalid MQTT device identity");
return `dc/mqtt/v1/users/${userId}/devices/${deviceId}/new_call`;
}
/** A per-device subscription that validates and observes shadow notifications. */
export class MqttTransport {
/** Bind verified registration identity and RemoteChannel's delivery/readiness callbacks once. */
constructor(config, userId, deviceId, onDoorbell, onReady, onMalformed = () => { },
/** Called when the receiver stops itself after start() resolved, so RemoteChannel can restart MQTT. */
onFailed = () => { }) {
this.config = config;
this.userId = userId;
this.deviceId = deviceId;
this.onDoorbell = onDoorbell;
this.onReady = onReady;
this.onMalformed = onMalformed;
this.onFailed = onFailed;
this.client = null;
this.stopped = false;
this.ready = false;
this.cancelStart = null;
this.topic = mqttDoorbellTopic(userId, deviceId);
}
/** Make one connection attempt and resolve after QoS 1 SUBACK and the readiness update. */
async start() {
if (this.client || this.stopped) {
throw new Error("MQTT receiver already started or stopped");
}
// Log only the hostname: credentials and raw broker errors must stay out of logs.
console.debug("[MQTT] Connecting to broker:", new URL(this.config.url).hostname);
const client = connect(this.config.url, {
...this.config.options,
reconnectPeriod: 0, // MQTT.js IClientOptions.reconnectPeriod: 0 ms disables automatic retries. RemoteChannel schedules them.
// Stable identity also lets an AWS policy restrict this certificate's Connect permission.
clientId: `dc-device-${this.deviceId}`,
});
this.client = client;
// Each result publish in flight adds a "close" and a "packetsend" listener, so 140 allows about
// 70 at once. Passing it only prints Node's MaxListeners warning; no message is dropped.
client.setMaxListeners(140);
await new Promise((resolve, reject) => {
let settled = false;
// Startup has several competing exits; settle once and always cancel its timer.
const finish = (error) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
this.cancelStart = null;
if (error) {
reject(error);
}
else {
resolve();
}
};
// Report a startup failure through start(), and a later disconnect through onFailed().
const stopWithError = (error) => {
if (this.stopped)
return;
const alreadyStarted = settled;
finish(error);
void this.stop().catch(() => { });
if (alreadyStarted)
this.onFailed();
};
// A connected socket without a granted subscription must not hang device startup.
const timer = setTimeout(() => stopWithError(new Error("MQTT connection/subscription timed out")), this.config.options.connectTimeout ?? CONNECT_TIMEOUT_MS);
this.cancelStart = () => finish(new Error("MQTT receiver stopped"));
client.once("connect", () => {
if (this.stopped) {
return;
}
// A TCP connection alone cannot receive commands.
client.subscribe(this.topic, { qos: 1 }, (error, granted) => {
if (this.stopped || !client.connected) {
return;
}
if (error ||
granted?.length !== 1 ||
granted[0].topic !== this.topic ||
granted[0].qos !== 1) {
stopWithError(new Error("MQTT device subscription refused"));
return;
}
// Reject downgraded/foreign grants above, then let RemoteChannel persist capability.
// Recheck after that await so a stop/close cannot resolve stale startup as ready.
this.ready = true;
void this.onReady(true)
.then(() => {
if (!this.stopped && this.ready) {
// Report usable command delivery only after the broker grants the subscription.
console.debug("[MQTT] Connected and subscribed; receiving doorbells");
finish();
}
})
.catch(() => stopWithError(new Error("MQTT readiness update failed")));
});
});
client.once("close", () => stopWithError(new Error("MQTT connection closed")));
// Raw TLS/broker errors can include certificate paths or broker-provided sensitive text.
client.on("error", () => { });
// Treat broker input as untrusted before RemoteChannel performs any database read.
// Reject retained backlog and oversized data before parsing, then enforce exact identity.
client.on("message", (topic, bytes, packet) => {
console.debug("[MQTT] Doorbell received");
const invalid = () => {
try {
this.onMalformed();
}
catch {
/* analytics is best effort */
}
};
if (this.stopped || !this.ready)
return;
if (topic !== this.topic || packet.retain) {
invalid();
return;
}
let payload;
try {
// MQTT over TLS hands over whole packets, so a payload can't arrive in part; its shape is checked below.
payload = JSON.parse(bytes.toString("utf8"));
}
catch {
invalid();
return;
}
const keys = payload && typeof payload === "object" ? Object.keys(payload) : [];
const hasExecutionFlag = keys.includes("IS_MQTT_EXECUTION_ENABLED");
const baseKeyCount = 3 + Number(hasExecutionFlag);
if (keys.length !== baseKeyCount ||
(hasExecutionFlag && typeof payload.IS_MQTT_EXECUTION_ENABLED !== "boolean") ||
keys.some((key) => ![
"call_id",
"user_id",
"device_id",
...(hasExecutionFlag ? ["IS_MQTT_EXECUTION_ENABLED"] : []),
].includes(key)) ||
typeof payload?.call_id !== "string" ||
!ID.test(payload.call_id) ||
payload.user_id !== this.userId ||
payload.device_id !== this.deviceId) {
invalid();
return;
}
observeTransport({ stage: 'received_from_backend', callId: payload.call_id, deviceId: this.deviceId, userId: this.userId, transport: 'mqtt' });
console.debug("[MQTT] Observed doorbell notification");
void this.onDoorbell(payload).catch(() => { });
});
});
}
/** Publish one bounded result attempt without queuing it for a later connection. */
async publishResult(callId, originInstance) {
if (![callId, originInstance].every((value) => typeof value === "string" && ID.test(value))) {
throw new Error("Invalid MQTT result identity");
}
const client = this.client;
if (this.stopped ||
!this.ready ||
!client?.connected) {
throw new Error("MQTT result transport unavailable");
}
const topic = `dc/mqtt/v1/users/${this.userId}/devices/${this.deviceId}/result-${originInstance}`;
// Buffer identity keeps concurrent publishes of the same call separate locally.
// need to verify that payload is correct and this is what expected on other side.
const payload = Buffer.from(JSON.stringify({ call_id: callId }));
try {
await new Promise((resolve, reject) => {
let settled = false;
let messageId;
const finish = (error) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
client.off("close", onClose);
client.off("packetsend", onPacket);
if (error) {
// Only the application retries; discard an unacknowledged packet.
if (messageId !== undefined)
client.removeOutgoingMessage(messageId);
reject(error);
}
else {
resolve();
}
};
const onClose = () => finish(new Error("MQTT disconnected before result acknowledgement"));
const onPacket = (packet) => {
if (packet.cmd === "publish" &&
packet.topic === topic &&
packet.payload === payload)
messageId = packet.messageId;
};
// A timeout settles only this publish: finish() removes its own listeners and outgoing
// message, and the connection stays up for the others.
const timer = setTimeout(() => finish(new Error("MQTT result acknowledgement timed out")), 5000);
client.once("close", onClose);
client.on("packetsend", onPacket);
try {
observeTransport({ stage: 'publish_from_device', callId, deviceId: this.deviceId, userId: this.userId, transport: 'mqtt' });
client.publish(topic, payload, { qos: 1, retain: false }, (error) => {
// MQTT.js can fail pending publishes during shutdown before their close listeners run.
if (error && (this.stopped || !client.connected))
return onClose();
finish(error ? new Error("MQTT result publish failed") : undefined);
});
}
catch {
finish(new Error("MQTT result publish failed"));
}
});
}
finally {
}
}
/** Stop reconnects, reject pending startup and withdraw readiness on sign-out/shutdown. */
async stop() {
if (this.stopped)
return;
this.stopped = true;
this.ready = false;
this.cancelStart?.();
// Force socket closure: teardown must not wait for broker acknowledgements.
this.client?.end(true);
this.client = null;
await this.onReady(false);
}
}