"use strict"; // src/electron/khaos/networkService.js var import_node_net = require("node:net"); // src/electron/khaos/envelopeStream.js var MAX_MESSAGE_BYTES = 16777215; var EnvelopeStream = class { constructor(deliver, maxBodyBytes = MAX_MESSAGE_BYTES) { this.deliver = deliver; this.maxBodyBytes = maxBodyBytes; this.reset(); } reset() { this.part = "tag"; this.integer = 0; this.digits = 0; this.messageId = 0; this.body = null; this.written = 0; } push(chunk) { let cursor = 0; while (cursor < chunk.byteLength) { if (this.part === "body") { const amount = Math.min(chunk.byteLength - cursor, this.body.byteLength - this.written); this.body.set(chunk.subarray(cursor, cursor + amount), this.written); this.written += amount; cursor += amount; if (this.written === this.body.byteLength && !this.finish()) return; continue; } const byte = chunk[cursor++]; if (this.digits === 4 && byte > 15) throw new Error("Envelope header exceeds uint32"); this.integer += (byte & 127) * 128 ** this.digits; this.digits++; if (byte & 128) continue; const value = this.integer; this.integer = 0; this.digits = 0; if (this.part === "tag") { if (value < 10 || value % 8 !== 2) throw new Error("Envelope must contain a nonzero LEN field"); this.messageId = Math.floor(value / 8); this.part = "length"; } else { if (value > this.maxBodyBytes) throw new Error(`Envelope body exceeds ${this.maxBodyBytes} bytes`); this.body = new Uint8Array(value); this.written = 0; this.part = "body"; if (value === 0 && !this.finish()) return; } } } finish() { const messageId = this.messageId; const payload = this.body.buffer; this.reset(); return this.deliver(messageId, payload) !== false; } }; // src/renderer/khaos/binary/realmBytes.js var typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get; var arrayBufferLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; function isUint8Array(value) { return typedArrayName.call(value) === "Uint8Array"; } // src/electron/khaos/networkService.js var validId = (value) => Number.isSafeInteger(value) && value >= 0; var isLoopbackHost = (host) => /^(?:localhost|127(?:\.\d{1,3}){3}|::1|\[::1\])$/iu.test(host); var errorText = (error) => error instanceof Error ? error.message : String(error); var post = (port, message) => { try { port?.postMessage(message); } catch { } }; var NetworkService = class { constructor(parent, { createSocket = () => new import_node_net.Socket(), connectTimeoutMs = 1e4, readTimeoutMs = 12e4, schedule = setTimeout, cancel = clearTimeout } = {}) { this.parent = parent; this.createSocket = createSocket; this.connectTimeoutMs = connectTimeoutMs; this.readTimeoutMs = readTimeoutMs; this.schedule = schedule; this.cancel = cancel; this.sessions = /* @__PURE__ */ new Map(); } accept(event) { const command = typeof event?.data?.type === "string" ? event.data : event; if (!command || !validId(command.sessionId)) return; const { type, sessionId } = command; if (type === "attach-data-port") { if (event.ports?.length === 1) this.attach(sessionId, event.ports[0]); else for (const port of event.ports ?? []) port.close(); } else if (type === "disconnect") { const session = this.sessions.get(sessionId); if (session) this.end(session, session.ready ? null : "connection cancelled"); } else if (type === "connect" && validId(command.requestId)) { this.open(command); } else if (type === "send" && validId(command.requestId) && isUint8Array(command.data)) { this.write(sessionId, command.requestId, command.data, this.parent); } } rejectConnect(command, error) { post(this.parent, { type: "connect-result", sessionId: command.sessionId, requestId: command.requestId, ok: false, error }); } open(command) { const { sessionId, requestId, host, port, security = "raw" } = command; if (this.sessions.has(sessionId)) { this.rejectConnect(command, `sessionId ${sessionId} already has a live connection`); return; } if (security !== "raw") { this.rejectConnect(command, "The Khaos client supports raw TCP only"); return; } if (typeof host !== "string" || !host.trim() || !Number.isInteger(port) || port < 1 || port > 65535) { this.rejectConnect(command, "Invalid network host or port"); return; } if (!isLoopbackHost(host)) { this.rejectConnect(command, "The Khaos client connects to its local connector only"); return; } let socket; try { socket = this.createSocket(); } catch (error) { this.rejectConnect(command, errorText(error)); return; } const session = { id: sessionId, requestId, socket, ready: false, closed: false, route: null, timer: null, sends: /* @__PURE__ */ new Map(), decoder: null }; session.decoder = new EnvelopeStream((messageId, payload) => { if (!this.active(session)) return false; post(session.route ?? this.parent, { type: "network-message", sessionId, messageId, payload }); return this.active(session); }); this.sessions.set(sessionId, session); socket.on("error", (error) => this.end(session, errorText(error))); socket.on("close", () => this.end(session, session.ready ? null : "connection closed before ready")); socket.on("data", (chunk) => { if (!this.active(session)) return; try { if (session.ready) this.armTimeout(session, this.readTimeoutMs, "read"); session.decoder.push(chunk); } catch (error) { this.end(session, errorText(error)); } }); socket.once("connect", () => { if (!this.active(session)) return; session.ready = true; this.armTimeout(session, this.readTimeoutMs, "read"); post(this.parent, { type: "network-status", sessionId, connected: true, error: null }); post(this.parent, { type: "connect-result", sessionId, requestId, ok: true, error: null }); }); this.armTimeout(session, this.connectTimeoutMs, "connect"); try { socket.setNoDelay(true); socket.connect({ host, port }); } catch (error) { this.end(session, errorText(error)); } } active(session) { return !session.closed && this.sessions.get(session.id) === session; } armTimeout(session, milliseconds, phase) { if (session.timer !== null) this.cancel(session.timer); session.timer = this.schedule(() => this.end(session, `${phase} timeout after ${milliseconds}ms`), milliseconds); session.timer?.unref?.(); } attach(sessionId, port) { const session = this.sessions.get(sessionId); if (!session || session.closed) { port.close(); return; } const previous = session.route; if (previous) { for (const [key, pending] of session.sends) { if (pending.reply === previous) this.ack(session, key, "network data port replaced"); } previous.close(); } session.route = port; port.on("message", (event) => { const command = typeof event?.data?.type === "string" ? event.data : event; if (!this.active(session) || session.route !== port || command?.type !== "send" || !validId(command.requestId) || !isUint8Array(command.data)) return; this.write(sessionId, command.requestId, command.data, port); }); port.on("close", () => { if (session.route !== port) return; session.route = null; for (const [key, pending] of session.sends) { if (pending.reply === port) this.ack(session, key, "network data port closed"); } }); port.start(); } write(sessionId, requestId, data, reply) { const result = (error) => post(reply, { type: "send-result", sessionId, requestId, ok: error === null, error }); const session = this.sessions.get(sessionId); if (!session?.ready || session.closed) { result(`sessionId ${sessionId} is not connected`); return; } const key = `${reply === this.parent ? "control" : "renderer"}:${requestId}`; if (session.sends.has(key)) { this.end(session, "Duplicate network send request"); return; } const pending = { reply, result }; session.sends.set(key, pending); try { session.socket.write(data, (error) => { if (session.sends.get(key) !== pending) return; this.ack(session, key, error ? errorText(error) : null); if (error) this.end(session, errorText(error)); }); } catch (error) { this.end(session, errorText(error)); } } ack(session, key, error) { const pending = session.sends.get(key); session.sends.delete(key); pending?.result(error); } end(session, error) { if (!this.active(session)) return; session.closed = true; this.sessions.delete(session.id); if (session.timer !== null) this.cancel(session.timer); session.timer = null; for (const key of session.sends.keys()) this.ack(session, key, error ?? "connection closed before packet write completed"); session.decoder.reset(); session.socket.destroy(); session.route?.close(); session.route = null; if (session.ready) { post(this.parent, { type: "network-status", sessionId: session.id, connected: false, error }); } else { this.rejectConnect({ sessionId: session.id, requestId: session.requestId }, error); } } close() { for (const session of this.sessions.values()) this.end(session, "network service closed"); } }; function bindNetworkService(parent, options) { const service = new NetworkService(parent, options); parent.on("message", (event) => service.accept(event)); parent.on("close", () => service.close()); return service; } // src/electron/network-service.js if (!process.parentPort) throw new Error("network-service requires process.parentPort"); bindNetworkService(process.parentPort); //# sourceMappingURL=network-service.cjs.map