feat: add TLS for node bridge

This commit is contained in:
Peter Steinberger
2026-01-16 05:28:33 +00:00
parent 1656f491fd
commit 1ab1e312b2
36 changed files with 1161 additions and 180 deletions

View File

@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import net from "node:net";
import os from "node:os";
import tls from "node:tls";
import { resolveCanvasHostUrl } from "../../canvas-host-url.js";
@@ -47,7 +48,8 @@ export async function startNodeBridgeServer(opts: NodeBridgeServerOpts): Promise
const loopbackHost = "127.0.0.1";
const listeners: Array<{ host: string; server: net.Server }> = [];
const primary = net.createServer(onConnection);
const createServer = () => (opts.tls ? tls.createServer(opts.tls, onConnection) : net.createServer(onConnection));
const primary = createServer();
await new Promise<void>((resolve, reject) => {
const onError = (err: Error) => reject(err);
primary.once("error", onError);
@@ -65,7 +67,7 @@ export async function startNodeBridgeServer(opts: NodeBridgeServerOpts): Promise
const port = typeof address === "object" && address ? address.port : opts.port;
if (shouldAlsoListenOnLoopback(opts.host)) {
const loopback = net.createServer(onConnection);
const loopback = createServer();
try {
await new Promise<void>((resolve, reject) => {
const onError = (err: Error) => reject(err);

View File

@@ -0,0 +1,152 @@
import { execFile } from "node:child_process";
import { X509Certificate } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import tls from "node:tls";
import { promisify } from "node:util";
import type { BridgeTlsConfig } from "../../../config/types.gateway.js";
import { CONFIG_DIR, ensureDir, resolveUserPath, shortenHomeInString } from "../../../utils.js";
const execFileAsync = promisify(execFile);
export type BridgeTlsRuntime = {
enabled: boolean;
required: boolean;
certPath?: string;
keyPath?: string;
caPath?: string;
fingerprintSha256?: string;
tlsOptions?: tls.TlsOptions;
error?: string;
};
function normalizeFingerprint(input: string): string {
return input.replace(/[^a-fA-F0-9]/g, "").toLowerCase();
}
async function fileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
async function generateSelfSignedCert(params: {
certPath: string;
keyPath: string;
log?: { info?: (msg: string) => void };
}): Promise<void> {
const certDir = path.dirname(params.certPath);
const keyDir = path.dirname(params.keyPath);
await ensureDir(certDir);
if (keyDir !== certDir) {
await ensureDir(keyDir);
}
await execFileAsync("openssl", [
"req",
"-x509",
"-newkey",
"rsa:2048",
"-sha256",
"-days",
"3650",
"-nodes",
"-keyout",
params.keyPath,
"-out",
params.certPath,
"-subj",
"/CN=clawdbot-bridge",
]);
await fs.chmod(params.keyPath, 0o600).catch(() => {});
await fs.chmod(params.certPath, 0o600).catch(() => {});
params.log?.info?.(
`bridge tls: generated self-signed cert at ${shortenHomeInString(params.certPath)}`,
);
}
export async function loadBridgeTlsRuntime(
cfg: BridgeTlsConfig | undefined,
log?: { info?: (msg: string) => void; warn?: (msg: string) => void },
): Promise<BridgeTlsRuntime> {
if (!cfg || cfg.enabled !== true) return { enabled: false, required: false };
const autoGenerate = cfg.autoGenerate !== false;
const baseDir = path.join(CONFIG_DIR, "bridge", "tls");
const certPath = resolveUserPath(cfg.certPath ?? path.join(baseDir, "bridge-cert.pem"));
const keyPath = resolveUserPath(cfg.keyPath ?? path.join(baseDir, "bridge-key.pem"));
const caPath = cfg.caPath ? resolveUserPath(cfg.caPath) : undefined;
const hasCert = await fileExists(certPath);
const hasKey = await fileExists(keyPath);
if (!hasCert && !hasKey && autoGenerate) {
try {
await generateSelfSignedCert({ certPath, keyPath, log });
} catch (err) {
return {
enabled: false,
required: true,
certPath,
keyPath,
error: `bridge tls: failed to generate cert (${String(err)})`,
};
}
}
if (!(await fileExists(certPath)) || !(await fileExists(keyPath))) {
return {
enabled: false,
required: true,
certPath,
keyPath,
error: "bridge tls: cert/key missing",
};
}
try {
const cert = await fs.readFile(certPath, "utf8");
const key = await fs.readFile(keyPath, "utf8");
const ca = caPath ? await fs.readFile(caPath, "utf8") : undefined;
const x509 = new X509Certificate(cert);
const fingerprintSha256 = normalizeFingerprint(x509.fingerprint256 ?? "");
if (!fingerprintSha256) {
return {
enabled: false,
required: true,
certPath,
keyPath,
caPath,
error: "bridge tls: unable to compute certificate fingerprint",
};
}
return {
enabled: true,
required: true,
certPath,
keyPath,
caPath,
fingerprintSha256,
tlsOptions: {
cert,
key,
ca,
minVersion: "TLSv1.2",
},
};
} catch (err) {
return {
enabled: false,
required: true,
certPath,
keyPath,
caPath,
error: `bridge tls: failed to load cert (${String(err)})`,
};
}
}

View File

@@ -1,3 +1,5 @@
import type { TlsOptions } from "node:tls";
import type { NodePairingPendingRequest } from "../../node-pairing.js";
export type BridgeHelloFrame = {
@@ -122,6 +124,7 @@ export type NodeBridgeClientInfo = {
export type NodeBridgeServerOpts = {
host: string;
port: number; // 0 = ephemeral
tls?: TlsOptions;
pairingBaseDir?: string;
canvasHostPort?: number;
canvasHostHost?: string;