feat: direct TCP URI with SSL toggle and optional password auth (#635)

* feat: direct TCP URI with SSL toggle and optional password auth

Replaces the heuristic-driven direct-connection model with a user-controlled
one. The Add Host dialog now exposes structured Host, Port, "Use SSL", and
masked Password fields that compose the canonical
`tcp://host:port?ssl=true&password=xxx` URI used as the storage form.

The daemon gains optional shared-secret auth: `Authorization: Bearer <pw>` on
HTTP and `Sec-WebSocket-Protocol: paseo.bearer.<pw>` on the WS upgrade
(browser WebSocket can't set custom headers). Configured via config.json
`auth.password` or `PASEO_PASSWORD` env. Off by default — old clients keep
working unchanged.

The `port === 443` heuristic for ws/wss is gone; the explicit `useTls` flag
drives scheme selection at every call site.

* fix: stabilize direct tcp auth ci checks

* fix: restore fetch stub in bootstrap smoke test

* fix(app): collapse Advanced section in add-host modal

* feat(server): hash daemon password in config

* fix: update lockfile signatures and Nix hash

* Improve direct TCP auth failures

* Fix workspace cwd updates after rebase

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Mohamed Boudra
2026-04-30 22:05:49 +08:00
committed by GitHub
co-authored by github-actions[bot] <github-actions[bot]@users.noreply.github.com>
parent 30f7842e8f
commit 088a6c14c0
48 changed files with 1829 additions and 129 deletions
@@ -3,6 +3,7 @@ import { startCommand } from "./start.js";
import { runStatusCommand } from "./status.js";
import { runStopCommand } from "./stop.js";
import { runRestartCommand } from "./restart.js";
import { runSetPasswordCommand } from "./set-password.js";
import { pairCommand } from "./pair.js";
import { withOutput } from "../../output/index.js";
import { addJsonOption } from "../../utils/command-options.js";
@@ -60,5 +61,13 @@ export function createDaemonCommand(): Command {
}),
);
addJsonOption(
daemon
.command("set-password")
.description("Prompt for and save a hashed daemon password to config.json"),
)
.option("--home <path>", "Paseo home directory (default: ~/.paseo)")
.action(withOutput(runSetPasswordCommand));
return daemon;
}
@@ -0,0 +1,126 @@
import path from "node:path";
import type { Command } from "commander";
import { isCancel, password as passwordPrompt } from "@clack/prompts";
import {
hashDaemonPassword,
loadPersistedConfig,
savePersistedConfig,
type PersistedConfig,
} from "@getpaseo/server";
import type {
CommandError,
CommandOptions,
OutputOptions,
OutputSchema,
SingleResult,
} from "../../output/index.js";
import { resolveLocalPaseoHome } from "./local-daemon.js";
const CONFIG_FILENAME = "config.json";
interface SetPasswordResult {
action: "password_set";
configPath: string;
restartCommand: string;
message: string;
}
export type PromptPassword = (message: string) => Promise<string | symbol>;
export interface SetPasswordOptions {
home?: string;
promptPassword?: PromptPassword;
}
const setPasswordResultSchema: OutputSchema<SetPasswordResult> = {
idField: "action",
columns: [
{ header: "STATUS", field: "action", color: () => "green" },
{ header: "CONFIG", field: "configPath" },
{ header: "RESTART", field: "restartCommand" },
],
renderHuman: (result, options: OutputOptions) => {
const data = result.data as SetPasswordResult;
const rows = [
`Password written to ${data.configPath}`,
"Restart the daemon for the change to take effect.",
`Run: ${data.restartCommand}`,
];
if (options.format === "table") {
return rows.join("\n");
}
return data.message;
},
};
function createCommandError(code: string, message: string, details?: string): CommandError {
return { code, message, ...(details ? { details } : {}) };
}
async function promptForPassword(promptPassword: PromptPassword): Promise<string> {
const first = await promptPassword("New daemon password");
if (isCancel(first)) {
throw createCommandError("PASSWORD_CANCELLED", "Password update cancelled");
}
if (typeof first !== "string" || first.length === 0) {
throw createCommandError("PASSWORD_REQUIRED", "Password cannot be empty");
}
const second = await promptPassword("Confirm daemon password");
if (isCancel(second)) {
throw createCommandError("PASSWORD_CANCELLED", "Password update cancelled");
}
if (first !== second) {
throw createCommandError("PASSWORD_MISMATCH", "Passwords do not match");
}
return first;
}
export async function setDaemonPasswordInConfig(
newPassword: string,
options: SetPasswordOptions = {},
): Promise<SetPasswordResult> {
const paseoHome = resolveLocalPaseoHome(options.home);
const configPath = path.join(paseoHome, CONFIG_FILENAME);
const persisted = loadPersistedConfig(paseoHome);
const nextConfig: PersistedConfig = {
...persisted,
daemon: {
...persisted.daemon,
auth: {
...persisted.daemon?.auth,
password: hashDaemonPassword(newPassword),
},
},
};
savePersistedConfig(paseoHome, nextConfig);
return {
action: "password_set",
configPath,
restartCommand: "paseo daemon restart",
message: `Password written to ${configPath}\nRestart the daemon for the change to take effect.\nRun: paseo daemon restart`,
};
}
export async function runSetPasswordCommand(
options: CommandOptions,
_command: Command,
): Promise<SingleResult<SetPasswordResult>> {
const promptPassword =
typeof options.promptPassword === "function"
? (options.promptPassword as PromptPassword)
: (message: string) => passwordPrompt({ message });
const newPassword = await promptForPassword(promptPassword);
const result = await setDaemonPasswordInConfig(newPassword, {
home: typeof options.home === "string" ? options.home : undefined,
});
return {
type: "single",
data: result,
schema: setPasswordResultSchema,
};
}
+63 -10
View File
@@ -1,10 +1,14 @@
import { existsSync, readFileSync } from "node:fs";
import {
loadConfig,
resolvePaseoHome,
DaemonClient,
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
loadConfig,
normalizeHostPort,
parseConnectionUri,
parseConnectionOfferFromUrl,
DaemonClient,
resolvePaseoHome,
shouldUseTlsForDefaultHostedRelay,
type ConnectionOffer,
type WebSocketLike,
} from "@getpaseo/server";
@@ -46,6 +50,27 @@ export function normalizeDaemonHost(raw: string): string | null {
return null;
}
if (trimmed.startsWith("tcp://")) {
try {
const parsed = parseConnectionUri(trimmed);
const endpoint = normalizeHostPort(
parsed.isIpv6 ? `[${parsed.host}]:${parsed.port}` : `${parsed.host}:${parsed.port}`,
);
const query = new URLSearchParams();
if (parsed.useTls) {
query.set("ssl", "true");
}
if (parsed.password) {
query.set("password", parsed.password);
}
const queryString = query.toString();
const suffix = queryString ? `?${queryString}` : "";
return `tcp://${endpoint}${suffix}`;
} catch {
return null;
}
}
if (
trimmed.startsWith("unix://") ||
trimmed.startsWith("pipe://") ||
@@ -174,21 +199,37 @@ export function resolveDaemonTarget(host: string): DaemonTarget {
};
}
if (trimmed.startsWith("tcp://")) {
const parsed = parseConnectionUri(trimmed);
const endpoint = normalizeHostPort(
parsed.isIpv6 ? `[${parsed.host}]:${parsed.port}` : `${parsed.host}:${parsed.port}`,
);
return {
type: "tcp",
url: buildDaemonWebSocketUrl(endpoint, { useTls: parsed.useTls }),
};
}
return {
type: "tcp",
url: `ws://${trimmed}/ws`,
};
}
export function resolveDaemonPassword(host: string): string | undefined {
const trimmed = host.trim();
return trimmed.startsWith("tcp://") ? parseConnectionUri(trimmed).password : undefined;
}
/**
* Create a WebSocket factory that works in Node.js
*/
function createNodeWebSocketFactory() {
return (
url: string,
options?: { headers?: Record<string, string>; socketPath?: string },
options?: { headers?: Record<string, string>; protocols?: string[]; socketPath?: string },
): WebSocketLike => {
return new WebSocket(url, {
return new WebSocket(url, options?.protocols, {
headers: options?.headers,
...(options?.socketPath ? { socketPath: options.socketPath } : {}),
}) as unknown as WebSocketLike;
@@ -201,6 +242,7 @@ function createNodeWebSocketFactory() {
*/
async function tryConnectHost(
host: string,
password: string | undefined,
clientId: string,
timeout: number,
nodeWebSocketFactory: ReturnType<typeof createNodeWebSocketFactory>,
@@ -211,10 +253,15 @@ async function tryConnectHost(
clientId,
clientType: "cli",
appVersion: resolveCliVersion(),
password,
connectTimeoutMs: timeout,
webSocketFactory: (url: string, config?: { headers?: Record<string, string> }) =>
webSocketFactory: (
url: string,
config?: { headers?: Record<string, string>; protocols?: string[] },
) =>
nodeWebSocketFactory(url, {
headers: config?.headers,
protocols: config?.protocols,
...(target.type === "ipc" ? { socketPath: target.socketPath } : {}),
}),
reconnect: { enabled: false },
@@ -239,6 +286,7 @@ async function connectViaRelayOffer(
endpoint: offer.relay.endpoint,
serverId: offer.serverId,
role: "client",
useTls: shouldUseTlsForDefaultHostedRelay(offer.relay.endpoint),
});
const client = new DaemonClient({
@@ -247,8 +295,10 @@ async function connectViaRelayOffer(
clientType: "cli",
appVersion: resolveCliVersion(),
connectTimeoutMs: timeout,
webSocketFactory: (target: string, config?: { headers?: Record<string, string> }) =>
nodeWebSocketFactory(target, { headers: config?.headers }),
webSocketFactory: (
target: string,
config?: { headers?: Record<string, string>; protocols?: string[] },
) => nodeWebSocketFactory(target, { headers: config?.headers, protocols: config?.protocols }),
e2ee: { enabled: true, daemonPublicKeyB64: offer.daemonPublicKeyB64 },
reconnect: { enabled: false },
});
@@ -293,8 +343,11 @@ export async function connectToDaemon(options?: ConnectOptions): Promise<DaemonC
throw new Error(`Unable to connect to Paseo daemon via ${hosts.join(", ")}`);
}
const host = hosts[index] as string;
const result = await tryConnectHost(host, clientId, timeout, nodeWebSocketFactory);
if ("client" in result) return result.client;
const password = resolveDaemonPassword(host);
const result = await tryConnectHost(host, password, clientId, timeout, nodeWebSocketFactory);
if ("client" in result) {
return result.client;
}
return tryNext(index + 1, result.error);
}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { Command } from "commander";
const JSON_OPTION_DESCRIPTION = "Output in JSON format";
const DAEMON_HOST_OPTION_DESCRIPTION =
"Daemon host target (default: local socket/pipe, then localhost:6767)";
"Daemon host target: host:port or tcp://host:port?ssl=true&password=secret (default: local socket/pipe, then localhost:6767)";
export function collectMultiple(value: string, previous: string[]): string[] {
return previous.concat([value]);
@@ -7,6 +7,7 @@ import path from "node:path";
import {
getDaemonHost,
normalizeDaemonHost,
resolveDaemonPassword,
resolveDaemonTarget,
resolveDefaultDaemonHosts,
} from "../src/utils/client.js";
@@ -37,20 +38,39 @@ console.log("=== CLI IPC Target Helpers ===\n");
}
{
console.log("Test 3: local unix socket paths normalize into IPC daemon targets");
console.log("Test 3: tcp URI host targets honor ssl=true");
const target = resolveDaemonTarget("tcp://example.com:6767?ssl=true&password=query-secret");
assert.deepStrictEqual(target, {
type: "tcp",
url: "wss://example.com:6767/ws",
});
console.log("✓ tcp URI host targets honor ssl=true\n");
}
{
console.log("Test 4: tcp URI hosts normalize into canonical direct TCP targets");
assert.strictEqual(
normalizeDaemonHost("tcp://Example.com:6767?ssl=true&password=query-secret"),
"tcp://Example.com:6767?ssl=true&password=query-secret",
);
console.log("✓ tcp URI hosts normalize into canonical direct TCP targets\n");
}
{
console.log("Test 5: local unix socket paths normalize into IPC daemon targets");
assert.strictEqual(normalizeDaemonHost("/tmp/paseo.sock"), "unix:///tmp/paseo.sock");
console.log("✓ local unix socket paths normalize into IPC daemon targets\n");
}
{
console.log("Test 3b: Windows absolute paths are NOT treated as unix sockets");
console.log("Test 5b: Windows absolute paths are NOT treated as unix sockets");
assert.strictEqual(normalizeDaemonHost("C:\\Users\\foo\\.paseo\\paseo.sock"), null);
assert.strictEqual(normalizeDaemonHost("D:\\project\\socket"), null);
console.log("✓ Windows absolute paths are not treated as unix sockets\n");
}
{
console.log("Test 4: default host resolution tries local IPC first, then localhost fallback");
console.log("Test 6: default host resolution tries local IPC first, then localhost fallback");
const paseoHome = mkdtempSync(path.join(os.tmpdir(), "paseo-client-targets-"));
try {
mkdirSync(paseoHome, { recursive: true });
@@ -78,7 +98,7 @@ console.log("=== CLI IPC Target Helpers ===\n");
}
{
console.log("Test 5: configured TCP host is preserved before the localhost fallback");
console.log("Test 7: configured TCP host is preserved before the localhost fallback");
const paseoHome = mkdtempSync(path.join(os.tmpdir(), "paseo-client-targets-tcp-"));
try {
assert.deepStrictEqual(
@@ -95,13 +115,13 @@ console.log("=== CLI IPC Target Helpers ===\n");
}
{
console.log("Test 6: CLI app version resolves for daemon hello compatibility");
console.log("Test 8: CLI app version resolves for daemon hello compatibility");
assert.match(resolveCliVersion(), /^\d+\.\d+\.\d+/);
console.log("✓ CLI app version resolves for daemon hello compatibility\n");
}
{
console.log("Test 7: local IPC still takes priority over configured TCP hosts");
console.log("Test 9: local IPC still takes priority over configured TCP hosts");
const paseoHome = mkdtempSync(path.join(os.tmpdir(), "paseo-client-targets-order-"));
try {
mkdirSync(paseoHome, { recursive: true });
@@ -122,4 +142,15 @@ console.log("=== CLI IPC Target Helpers ===\n");
console.log("✓ local IPC still takes priority over configured TCP hosts\n");
}
{
console.log("Test 10: daemon password resolution uses only the TCP URI query");
assert.strictEqual(
resolveDaemonPassword("tcp://example.com:6767?ssl=true&password=query-secret"),
"query-secret",
);
assert.strictEqual(resolveDaemonPassword("tcp://missing.example:6767"), undefined);
assert.strictEqual(resolveDaemonPassword("example.com:6767"), undefined);
console.log("✓ daemon password resolution uses only the TCP URI query\n");
}
console.log("=== All CLI IPC target tests passed ===");
@@ -0,0 +1,107 @@
#!/usr/bin/env npx tsx
import assert from "node:assert";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Command } from "commander";
import { isBearerTokenValid } from "@getpaseo/server";
import {
runSetPasswordCommand,
setDaemonPasswordInConfig,
type PromptPassword,
} from "../src/commands/daemon/set-password.ts";
console.log("=== Daemon Set Password Command ===\n");
const root = await mkdtemp(join(tmpdir(), "paseo-set-password-"));
const paseoHome = join(root, ".paseo");
function promptSequence(values: string[]): PromptPassword {
return async () => {
const value = values.shift();
if (value === undefined) {
throw new Error("prompt called too many times");
}
return value;
};
}
try {
{
console.log("Test 1: setDaemonPasswordInConfig writes hash and preserves config fields");
await mkdir(paseoHome, { recursive: true });
await writeFile(
join(paseoHome, "config.json"),
`${JSON.stringify(
{
version: 1,
daemon: {
listen: "127.0.0.1:9999",
relay: { enabled: false },
},
app: { baseUrl: "https://app.paseo.sh" },
},
null,
2,
)}\n`,
);
const result = await setDaemonPasswordInConfig("shared-secret", { home: paseoHome });
const config = JSON.parse(await readFile(join(paseoHome, "config.json"), "utf-8"));
assert.strictEqual(result.configPath, join(paseoHome, "config.json"));
assert.strictEqual(result.restartCommand, "paseo daemon restart");
assert.strictEqual(config.daemon.listen, "127.0.0.1:9999");
assert.strictEqual(config.daemon.relay.enabled, false);
assert.notStrictEqual(config.daemon.auth.password, "shared-secret");
assert.match(config.daemon.auth.password, /^\$2[aby]\$12\$/);
assert.strictEqual(
isBearerTokenValid({ password: config.daemon.auth.password, token: "shared-secret" }),
true,
);
console.log("✓ set-password writes bcrypt hash without clobbering config\n");
}
{
console.log("Test 2: command prompts twice and accepts matching confirmation");
const result = await runSetPasswordCommand(
{
home: paseoHome,
promptPassword: promptSequence(["new-secret", "new-secret"]),
},
{} as Command,
);
const config = JSON.parse(await readFile(join(paseoHome, "config.json"), "utf-8"));
assert.strictEqual(result.data.action, "password_set");
assert.strictEqual(
isBearerTokenValid({ password: config.daemon.auth.password, token: "new-secret" }),
true,
);
console.log("✓ command accepts matching confirmation\n");
}
{
console.log("Test 3: command refuses mismatched confirmation");
await assert.rejects(
runSetPasswordCommand(
{
home: paseoHome,
promptPassword: promptSequence(["first-secret", "second-secret"]),
},
{} as Command,
),
(error: unknown) =>
typeof error === "object" &&
error !== null &&
"code" in error &&
error.code === "PASSWORD_MISMATCH",
);
console.log("✓ command refuses password mismatch\n");
}
} finally {
await rm(root, { recursive: true, force: true });
}
console.log("=== Daemon Set Password Command Tests Passed ===");