Files
paseo/packages/protocol/src/daemon-endpoints.ts
T
Mohamed Boudra e1c769c018 Make password-protected daemons work across local and remote connections (#5393)
* feat(auth): authenticate daemon clients through hello

Give local CLI and desktop clients a per-run credential while remote clients send the host password inside the protocol. Keep relay passwordless admission for this mobile release so existing saved hosts keep working until the follow-up enforcement release.

Move password recovery for saved hosts into host settings and keep pairing credentials in the add flow. Include isolated web QA evidence for both flows.

* fix(auth): preserve Hub bootstrap and local credential expectations

Hub-owned sockets already carry admission; keep their hello handling synchronous through session bootstrap while resolving credentials asynchronously for ordinary sockets. Keep the resolver out of lightweight configuration imports.

Update CLI expectations for same-home credentials, let a rejected connection yield to another usable connection, and clear pairing secrets when add-flow targets change.

* fix(pairing): retain passwords across edits to the same target

Track the last valid pairing host while a URI is edited. This preserves an entered password for whitespace and partial edits but clears it when a different host becomes the target.

* test(auth): align local credential checks across platforms

Expect the CLI to authenticate through the credential in its selected home, and verify POSIX file modes only where Node exposes them.

* feat(app): move host password into a settings row with a modal

The host page rendered an always-visible password form above Name on every
host. Replace it with a Password row under a Security section below
Appearance; tapping it opens a modal with Save and, when a password is saved,
Clear. The connection-error callout keeps its guidance and gains a Set
password button that opens the same modal. Drop the unused
pairing.hostPassword body/reopen/saveError strings.

* chore: remove committed QA screenshots

QA evidence stays out of the repository; the PR body describes it in words.

* feat(app): keep the host password out of the host page

The saved password is connection data, entered only when a host is added. A
Password setting on the host page reads as the daemon's own password, so the
row, modal, and callout button are gone. A rejected host shows the daemon's
reason with guidance to remove the host and add it again with the password.
useHostMutations no longer exposes setHostPassword; relay imports still set it
inside the runtime.

* feat(app): show host connection errors in an error alert

HostConnectionError renders the existing Alert with the connection error as
its title. Auth rejections add the re-add guidance as the description; other
errors show the title only. The Overview and Connections pages share it.

* style(app): soften alert borders to half-opacity accent

* feat(app): size alerts on the button scale

Alert takes a size prop (xs/sm/md/lg, default md) whose geometry lives next to
the button's in control-geometry: one font size for title and description, the
button icon size centered on the first text line, button padding and radius,
and a one-line alert as tall as the button of the same size. Consumers pick
sm among settings rows, cards, panels, and modals, and md when the alert is
the whole page or sheet state.

* style(app): roomier, rounder alerts with a tight title block

Alert sm padding returns to the original 12/16 and every size is at least
borderRadius.xl. Title and description sit a small gap apart with no line
height override. The icon slot carries a zero-width text strut in the alert's
font so the icon centers on the first line for titled, title-only, and
description-only alerts.

* refactor(app): align the alert icon with a centered lead row

Drop the zero-width strut. The icon and the alert's first text (title, else
description) share one row centered on each other; the description and actions
sit below, indented by the icon slot width plus gap so they start at the lead
text's left edge.

* refactor(app): drop the unused Alert icon override
2026-09-26 19:53:43 +02:00

302 lines
8.9 KiB
TypeScript

import type { ConnectionOfferV2 } from "./connection-offer.js";
export interface HostPortParts {
host: string;
port: number;
isIpv6: boolean;
}
export interface ConnectionUriParts extends HostPortParts {
useTls: boolean;
}
export interface ParsedConnectionUri extends ConnectionUriParts {
password?: string;
}
export interface ParsedRelayConnectionUri {
offer: ConnectionOfferV2;
password?: string;
}
export function parseRelayConnectionUri(input: string): ParsedRelayConnectionUri {
const trimmed = input.trim();
const connectIndex = trimmed.indexOf("#connect=");
const uri =
connectIndex >= 0
? decodeURIComponent(trimmed.slice(connectIndex + "#connect=".length))
: trimmed;
let url: URL;
try {
url = new URL(uri);
} catch {
throw new Error("Invalid relay connection URI");
}
if (url.protocol !== "relay:" || !url.hostname || !url.port || url.username || url.password) {
throw new Error("Invalid relay connection URI");
}
const serverId = decodeURIComponent(url.pathname.slice(1));
const key = url.searchParams.get("key");
if (!serverId || !key || serverId.includes("/")) {
throw new Error("Relay connection URI requires a server id and key");
}
const endpoint = normalizeHostPort(url.host);
const password = url.searchParams.get("password") || undefined;
return {
offer: {
v: 2,
serverId,
daemonPublicKeyB64: key,
relay: { endpoint, useTls: url.searchParams.get("ssl") === "true" },
},
...(password ? { password } : {}),
};
}
export function serializeRelayConnectionUri(parts: ParsedRelayConnectionUri): string {
const url = new URL(
`relay://${parts.offer.relay.endpoint}/${encodeURIComponent(parts.offer.serverId)}`,
);
url.searchParams.set("key", parts.offer.daemonPublicKeyB64);
if (parts.offer.relay.useTls) url.searchParams.set("ssl", "true");
if (parts.password) url.searchParams.set("password", parts.password);
return url.toString();
}
export type RelayRole = "server" | "client";
export type RelayProtocolVersion = "1" | "2";
export const CURRENT_RELAY_PROTOCOL_VERSION: RelayProtocolVersion = "2";
export const DEFAULT_RELAY_ENDPOINT = "relay.paseo.sh:443";
export function normalizeRelayProtocolVersion(
value: unknown,
fallback: RelayProtocolVersion = CURRENT_RELAY_PROTOCOL_VERSION,
): RelayProtocolVersion {
if (value == null) {
return fallback;
}
let normalized = "";
if (typeof value === "string") {
normalized = value.trim();
} else if (typeof value === "number") {
normalized = String(value);
}
if (!normalized) {
return fallback;
}
if (normalized === "1" || normalized === "2") {
return normalized;
}
throw new Error('Relay version must be "1" or "2"');
}
function parsePort(portStr: string, context: string): number {
const port = Number(portStr);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(`${context}: port must be between 1 and 65535`);
}
return port;
}
export function parseHostPort(input: string): HostPortParts {
const trimmed = input.trim();
if (!trimmed) {
throw new Error("Host is required");
}
// IPv6: [::1]:6767
if (trimmed.startsWith("[")) {
const match = trimmed.match(/^\[([^\]]+)\]:(\d{1,5})$/);
if (!match) {
throw new Error("Invalid host:port (expected [::1]:6767)");
}
const host = match[1].trim();
if (!host) throw new Error("Host is required");
const port = parsePort(match[2], "Invalid host:port");
return { host, port, isIpv6: true };
}
const match = trimmed.match(/^(.+):(\d{1,5})$/);
if (!match) {
throw new Error("Invalid host:port (expected localhost:6767)");
}
const host = match[1].trim();
if (!host) throw new Error("Host is required");
const port = parsePort(match[2], "Invalid host:port");
return { host, port, isIpv6: false };
}
export function normalizeHostPort(input: string): string {
const { host, port, isIpv6 } = parseHostPort(input);
return isIpv6 ? `[${host}]:${port}` : `${host}:${port}`;
}
export function parseConnectionUri(input: string): ParsedConnectionUri {
const trimmed = input.trim();
if (!trimmed) {
throw new Error("Connection URI is required");
}
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
throw new Error("Invalid connection URI");
}
if (parsed.protocol !== "tcp:") {
throw new Error("Connection URI protocol must be tcp:");
}
if (!parsed.hostname) {
throw new Error("Connection URI host is required");
}
if (!parsed.port) {
throw new Error("Connection URI port is required");
}
if (parsed.username || parsed.password) {
throw new Error("Connection URI userinfo is not supported");
}
const isIpv6 = parsed.hostname.startsWith("[") && parsed.hostname.endsWith("]");
const host = isIpv6 ? parsed.hostname.slice(1, -1) : parsed.hostname;
const password = parsed.searchParams.get("password") || undefined;
return {
host,
port: parsePort(parsed.port, "Invalid connection URI"),
isIpv6,
useTls: parsed.searchParams.get("ssl") === "true",
...(password ? { password } : {}),
};
}
export function serializeConnectionUri(parts: ConnectionUriParts): string {
return createConnectionUri(parts).toString();
}
export function serializeConnectionUriForStorage(parts: ParsedConnectionUri): string {
const url = createConnectionUri(parts);
if (parts.password) {
url.searchParams.set("password", parts.password);
}
return url.toString();
}
function createConnectionUri(parts: ConnectionUriParts): URL {
const hostPart = parts.isIpv6 ? `[${parts.host}]` : parts.host;
const url = new URL(`tcp://${hostPart}:${parts.port}`);
if (parts.useTls) {
url.searchParams.set("ssl", "true");
}
return url;
}
export function normalizeLoopbackToLocalhost(endpoint: string): string {
const { host, port, isIpv6 } = parseHostPort(endpoint);
if (host === "127.0.0.1" || (!isIpv6 && host === "0.0.0.0")) {
return `localhost:${port}`;
}
if (isIpv6 && (host === "::1" || host === "::")) {
return `localhost:${port}`;
}
return endpoint;
}
export function deriveLabelFromEndpoint(endpoint: string): string {
try {
const { host } = parseHostPort(endpoint);
return host || "Unnamed Host";
} catch {
return "Unnamed Host";
}
}
export interface WebSocketUrlOptions {
useTls: boolean;
}
export function buildDaemonWebSocketUrl(endpoint: string, opts: WebSocketUrlOptions): string {
const { host, port, isIpv6 } = parseHostPort(endpoint);
const protocol = opts.useTls ? "wss" : "ws";
const hostPart = isIpv6 ? `[${host}]` : host;
return new URL(`${protocol}://${hostPart}:${port}/ws`).toString();
}
export function buildRelayWebSocketUrl(params: {
endpoint: string;
useTls: boolean;
serverId: string;
role: RelayRole;
/**
* Per-connection routing identifier used by the daemon to open server data sockets.
* Clients should NOT provide this — the relay assigns a routing ID on connect.
*/
connectionId?: string;
version?: RelayProtocolVersion | 1 | 2;
}): string {
const { host, port, isIpv6 } = parseHostPort(params.endpoint);
const protocol = params.useTls ? "wss" : "ws";
const hostPart = isIpv6 ? `[${host}]` : host;
const url = new URL(`${protocol}://${hostPart}:${port}/ws`);
url.searchParams.set("serverId", params.serverId);
url.searchParams.set("role", params.role);
url.searchParams.set("v", normalizeRelayProtocolVersion(params.version));
if (params.connectionId) {
url.searchParams.set("connectionId", params.connectionId);
}
return url.toString();
}
/**
* @deprecated Migration fallback for stored relay connections/offers that predate
* explicit relay useTls. Delete after two release cycles.
*/
export function shouldUseTlsForDefaultHostedRelay(endpoint: string): boolean {
try {
const { port } = parseHostPort(endpoint);
return port === 443;
} catch {
return false;
}
}
export function extractHostPortFromWebSocketUrl(wsUrl: string): string {
const parsed = new URL(wsUrl);
if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
throw new Error("Invalid WebSocket URL protocol");
}
if (parsed.pathname.replace(/\/+$/, "") !== "/ws") {
throw new Error("Invalid WebSocket URL (expected /ws path)");
}
const host = parsed.hostname;
let port: number;
if (parsed.port) {
port = Number(parsed.port);
} else if (parsed.protocol === "wss:") {
port = 443;
} else {
port = 80;
}
if (!host) {
throw new Error("Invalid WebSocket URL (missing hostname)");
}
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("Invalid WebSocket URL (invalid port)");
}
const isIpv6 = host.includes(":") && !host.startsWith("[") && !host.endsWith("]");
return isIpv6 ? `[${host}]:${port}` : `${host}:${port}`;
}
export function isRelayClientWebSocketUrl(url: string): boolean {
try {
const parsed = new URL(url);
return parsed.searchParams.get("role") === "client" && parsed.searchParams.has("serverId");
} catch {
return false;
}
}