Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 513766c25a test(relay): cover repeated protected handshake replies
Repeat the real client hello over the relay and identify the repeated ready by its exact text. This keeps the binary framing assertion focused on application records.
2026-12-05 07:17:36 +01:00
Mohamed Boudra 0d7d002315 perf(relay): send ProtectedChannel text records as binary frames 2026-12-05 07:09:20 +01:00
11 changed files with 359 additions and 1299 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ wire record = (u16 BE ciphertextLength || ciphertext)+
The receiver rejects a record whose metadata disagrees between chunks, whose non-final chunks are not full, whose byte total differs from `totalLength`, or that has zero chunks, trailing bytes, reserved flags, or an invalid kind. Partial plaintext never reaches the application. Transport AD is empty, as the Noise spec writes it; framing authenticity comes from the metadata being inside the ciphertext. `packages/relay/src/protected-records.ts` owns this.
Frame kind is preserved on the wire the same way as legacy: text records are base64 WebSocket text, binary records are WebSocket binary when `binaryCiphertext` was negotiated.
When `binaryCiphertext` is negotiated, both text and binary records travel as WebSocket binary frames, because the authenticated `kind` byte inside the record carries the frame kind. Base64 WebSocket text records remain accepted on receive for older peers and when `binaryCiphertext` is not negotiated.
## Retries and failures
@@ -41,9 +41,6 @@ import {
connectDirectHost,
connectDirectHostExpectingPassword,
pasteIntoDirectHost,
pasteClipboardIntoDirectField,
pasteIntoMiddleOfDirectHost,
typeDirectHostCharacters,
fillDirectHostPromptPassword,
openCompactSettings,
expectCompactSettingsList,
@@ -59,7 +56,6 @@ import {
fillDirectHostUri,
expectDirectHostFormValues,
expectDirectHostSslEnabled,
expectDirectHostSslDisabled,
fillDirectHostAddress,
toggleDirectHostSsl,
expectDirectHostUriValue,
@@ -377,110 +373,6 @@ test.describe("Settings sidebar navigation", () => {
});
});
test("direct connection form smart-fills on paste without disrupting manual typing", async ({
page,
}) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await expectDirectConnectionMode(page, "Form");
await test.step("pasting localhost:port splits Host and Port", async () => {
await pasteClipboardIntoDirectField(page, "Host", "localhost:6768");
await expectDirectHostFormValues(page, { host: "localhost", port: "6768", password: "" });
await expectDirectHostSslDisabled(page);
});
await test.step("pasting an https URI populates Host, Port, and Use SSL", async () => {
await pasteClipboardIntoDirectField(page, "Host", "https://myhost.ts.net:7443/");
await expectDirectHostFormValues(page, { host: "myhost.ts.net", port: "7443", password: "" });
await expectDirectHostSslEnabled(page);
});
await test.step("pasting a full Paseo URI populates Host, Port, Use SSL, and Password", async () => {
await pasteClipboardIntoDirectField(
page,
"Host",
"tcp://100.91.42.18:6769?ssl=false&password=my%20secret",
);
await expectDirectHostFormValues(page, {
host: "100.91.42.18",
port: "6769",
password: "my secret",
});
await expectDirectHostSslDisabled(page);
});
await test.step("pasting https without a port defaults Port to 443", async () => {
await pasteClipboardIntoDirectField(page, "Host", "https://tunnel.example.test");
await expectDirectHostFormValues(page, {
host: "tunnel.example.test",
port: "443",
password: "my secret",
});
await expectDirectHostSslEnabled(page);
});
await test.step("typing bare IPv6 and pasting into the middle of Host stay literal", async () => {
await typeDirectHostCharacters(page, "2001:1234::1");
await expectDirectHostFormValues(page, {
host: "2001:1234::1",
port: "443",
password: "my secret",
});
await pasteIntoMiddleOfDirectHost(page, "example.com", 2, "sub:9000");
await expectDirectHostFormValues(page, {
host: "exsub:9000ample.com",
port: "443",
password: "my secret",
});
});
await test.step("pasting a tcp URI without password clears a previous host password", async () => {
await pasteClipboardIntoDirectField(page, "Host", "tcp://second.example.test:7443");
await expectDirectHostFormValues(page, {
host: "second.example.test",
port: "7443",
password: "",
});
await expectDirectHostSslDisabled(page);
});
await test.step("clicking Use SSL after typing an https URL keeps SSL enabled", async () => {
await expectDirectHostSslDisabled(page);
await typeDirectHostCharacters(page, "https://typed.example.test:7443");
await toggleDirectHostSsl(page);
await expectDirectHostFormValues(page, {
host: "typed.example.test",
port: "7443",
password: "",
});
await expectDirectHostSslEnabled(page);
});
await test.step("pasting a host:port into Port fills Host and Port", async () => {
await pasteClipboardIntoDirectField(page, "Port", "hetzner.tail8a2f.ts.net:6768");
await expectDirectHostFormValues(page, {
host: "hetzner.tail8a2f.ts.net",
port: "6768",
password: "",
});
});
await test.step("pasting a live daemon address connects cleanly", async () => {
await pasteClipboardIntoDirectField(page, "Host", `http://127.0.0.1:${getE2EDaemonPort()}/`);
await expectDirectHostFormValues(page, {
host: "127.0.0.1",
port: String(getE2EDaemonPort()),
password: "",
});
await expectDirectHostSslDisabled(page);
await connectDirectHost(page);
});
});
test("direct connection connects to a URI with Host blank", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
@@ -455,46 +455,6 @@ export async function pasteIntoDirectHost(page: Page, text: string): Promise<voi
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
}
export async function pasteClipboardIntoDirectField(
page: Page,
field: "Host" | "Port",
text: string,
options?: { replace?: boolean },
): Promise<void> {
const input = page.getByRole("textbox", { name: field, exact: true });
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate((value) => navigator.clipboard.writeText(value), text);
await input.click();
if (options?.replace ?? true) {
await page.keyboard.press("ControlOrMeta+a");
}
await page.keyboard.press("ControlOrMeta+v");
}
export async function typeDirectHostCharacters(page: Page, text: string): Promise<void> {
const input = page.getByRole("textbox", { name: "Host", exact: true });
await input.click();
await page.keyboard.press("ControlOrMeta+a");
await page.keyboard.press("Backspace");
await input.pressSequentially(text);
}
export async function pasteIntoMiddleOfDirectHost(
page: Page,
initialHost: string,
offset: number,
pastedText: string,
): Promise<void> {
await typeDirectHostCharacters(page, initialHost);
await page.keyboard.press("Home");
for (let index = 0; index < offset; index += 1) {
await page.keyboard.press("ArrowRight");
}
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate((value) => navigator.clipboard.writeText(value), pastedText);
await page.keyboard.press("ControlOrMeta+v");
}
export async function toggleDirectHostSsl(page: Page): Promise<void> {
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
}
@@ -1,9 +1,5 @@
import { describe, expect, it } from "vitest";
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
parseDirectConnectionPaste,
} from "./direct-connection-host";
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
const labels = {
hostRequired: "host required",
@@ -61,26 +57,6 @@ describe("buildDirectConnectionUri", () => {
).toBe("tcp://example.test:443?ssl=true&password=secret");
});
it("honors scheme, ssl, and password from a typed URI in Host", () => {
expect(
buildDirectConnectionUri(
{
host: "tcp://secure.example.test:7443?ssl=true&password=example",
port: "6767",
useTls: false,
password: "",
},
labels,
),
).toBe("tcp://secure.example.test:7443?ssl=true&password=example");
expect(
buildDirectConnectionUri(
{ host: "https://myhost.ts.net", port: "6767", useTls: false, password: "" },
labels,
),
).toBe("tcp://myhost.ts.net:443?ssl=true");
});
it.each(["", " ", "tcp://", "http:///path"])("requires a host for %j", (host) => {
expect(() => buildUri(host)).toThrow("host required");
});
@@ -88,102 +64,5 @@ describe("buildDirectConnectionUri", () => {
it("rejects an invalid port", () => {
expect(() => buildUri("100.66.69.36", "70000")).toThrow("invalid port");
expect(() => buildUri("100.66.69.36:0")).toThrow("invalid port");
expect(() => buildUri("[::1]:0x10")).toThrow("invalid port");
expect(() => buildUri("100.66.69.36", "0x10")).toThrow("invalid port");
});
});
describe("parseDirectConnectionPaste", () => {
it.each([
["localhost:6768", { host: "localhost", port: "6768" }],
[" localhost:6768\n", { host: "localhost", port: "6768" }],
["100.91.42.18:6767", { host: "100.91.42.18", port: "6767" }],
["hetzner.tail8a2f.ts.net:6768", { host: "hetzner.tail8a2f.ts.net", port: "6768" }],
["localhost:6768/", { host: "localhost", port: "6768" }],
["localhost:6768/ws", { host: "localhost", port: "6768" }],
["[::1]:6768", { host: "::1", port: "6768" }],
["[fe80::1]:7000/", { host: "fe80::1", port: "7000" }],
["[::1]", { host: "::1" }],
["localhost/", { host: "localhost" }],
["http://localhost:6768", { host: "localhost", port: "6768", useTls: false }],
["http://localhost:6768/", { host: "localhost", port: "6768", useTls: false }],
["http://myhost.ts.net", { host: "myhost.ts.net", port: "80", useTls: false }],
["https://myhost.ts.net:6767", { host: "myhost.ts.net", port: "6767", useTls: true }],
["https://myhost.ts.net:6767/", { host: "myhost.ts.net", port: "6767", useTls: true }],
["HTTPS://MyHost.ts.net", { host: "MyHost.ts.net", port: "443", useTls: true }],
["https://myhost.ts.net/", { host: "myhost.ts.net", port: "443", useTls: true }],
["ws://localhost:6768/ws", { host: "localhost", port: "6768", useTls: false }],
["ws://myhost.ts.net/ws", { host: "myhost.ts.net", port: "80", useTls: false }],
["wss://myhost.ts.net:6767/ws", { host: "myhost.ts.net", port: "6767", useTls: true }],
["wss://myhost.ts.net/ws", { host: "myhost.ts.net", port: "443", useTls: true }],
["wss://[2001:db8::1]:7443/ws", { host: "2001:db8::1", port: "7443", useTls: true }],
["tcp://localhost:6768", { host: "localhost", port: "6768", useTls: false, password: "" }],
[
"tcp://myhost.ts.net:6767?ssl=true",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "" },
],
[
"tcp://myhost.ts.net:6767?ssl=true&password=a%26b%3Dc+d",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "a&b=c d" },
],
[
"tcp://[::1]:7000?ssl=true&password=secret",
{ host: "::1", port: "7000", useTls: true, password: "secret" },
],
["tcp://myhost.ts.net", { host: "myhost.ts.net", useTls: false, password: "" }],
["tcp://myhost.ts.net?ssl=true", { host: "myhost.ts.net", useTls: true, password: "" }],
[
"https://myhost.ts.net:6767?password=pw",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "pw" },
],
[
"https://:my%20pass@myhost.ts.net:6767",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "my pass" },
],
[
"localhost:6768?ssl=true&password=pw",
{ host: "localhost", port: "6768", useTls: true, password: "pw" },
],
])("extracts fields from %j", (input, expected) => {
expect(parseDirectConnectionPaste(input)).toEqual(expected);
});
it.each([
"",
" ",
"localhost",
"100.91.42.18",
"::1",
"fe80::1",
"2001:db8::1",
"localhost:0",
"localhost:65536",
"localhost:70000",
"localhost:abc",
"localhost:",
"http://localhost:0",
"http://localhost:70000",
"http://localhost:abc",
"http://localhost:",
"tcp://localhost:abc",
"http://",
"https://",
"tcp://",
"http:///path",
":6768",
"[]:6768",
"ftp://example.com:21",
"ssh://user@host:22",
"fe80:abcd",
"my host:6768",
"line1\nlocalhost:6768",
"getpaseo/paseo",
"alice@example.com",
"alice@example.com/",
"relay://relay.paseo.test:443/srv_abc?key=k",
"https://app.paseo.sh/#connect=abc",
"https://app.paseo.sh/#offer=abc",
])("returns null for %j", (input) => {
expect(parseDirectConnectionPaste(input)).toBeNull();
});
});
@@ -19,297 +19,52 @@ export interface NormalizedDirectConnectionHost {
isIpv6: boolean;
}
export interface ParsedDirectConnectionAddress {
/** Lowercased scheme without `://`, if present (e.g. "tcp", "http", "https", "ws", "wss"). */
scheme: string | null;
host: string;
/** Explicit port text after `:`, if present (`""` when a trailing `:` had no port). */
port: string | null;
isIpv6: boolean;
/** Path suffix starting with `/`, or empty string when omitted. */
path: string;
/** Password from `?password=` (or URL userinfo when query password is absent), if present. */
password: string | null;
/** Explicit `ssl` query flag (`"true"` / `"false"`), or null when omitted. */
sslParam: boolean | null;
}
export interface DirectConnectionPasteFields {
host: string;
port?: string;
useTls?: boolean;
password?: string;
}
const SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
const DIGITS_ONLY_PATTERN = /^\d+$/;
const DIRECT_CONNECTION_SCHEMES = new Set(["tcp", "http", "https", "ws", "wss"]);
export function defaultPortForDirectScheme(scheme: string | null): string | null {
if (scheme === "https" || scheme === "wss") return "443";
if (scheme === "http" || scheme === "ws") return "80";
return null;
}
export function resolveDirectSchemeTls(
scheme: string | null,
sslParam: boolean | null,
): boolean | undefined {
if (scheme === "https" || scheme === "wss") return true;
if (scheme === "http" || scheme === "ws") return false;
if (scheme === "tcp") return sslParam === true;
return sslParam ?? undefined;
}
function decodeUserinfoComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function parseSslParam(value: string | null): boolean | null {
if (value === "true") return true;
if (value === "false") return false;
return null;
}
function parseValidPortNumber(raw: string): number | null {
if (!DIGITS_ONLY_PATTERN.test(raw)) return null;
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
return port;
}
function parseValidPort(raw: string): string | null {
const port = parseValidPortNumber(raw);
return port === null ? null : String(port);
}
function stripUserinfo(
authority: string,
hasScheme: boolean,
): { authority: string; password: string | null } {
const atIndex = hasScheme ? authority.lastIndexOf("@") : -1;
if (atIndex === -1) return { authority, password: null };
const userinfo = authority.slice(0, atIndex);
const hostPort = authority.slice(atIndex + 1);
const colonIndex = userinfo.indexOf(":");
if (colonIndex === -1) return { authority: hostPort, password: null };
const decoded = decodeUserinfoComponent(userinfo.slice(colonIndex + 1));
return { authority: hostPort, password: decoded || null };
}
function splitAuthorityHostPort(authority: string): {
host: string;
port: string | null;
isIpv6: boolean;
} {
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
if (bracketed) {
return {
host: bracketed[1] ?? "",
port: bracketed[2] ?? null,
isIpv6: true,
};
}
const parts = authority.split(":");
if (parts.length === 2) {
return { host: parts[0] ?? "", port: parts[1] ?? "", isIpv6: false };
}
return { host: authority, port: null, isIpv6: parts.length > 2 };
}
function hasInvalidPasteHost(host: string): boolean {
return !host || /[\s[\]@]/.test(host);
}
function resolvePastePort(address: ParsedDirectConnectionAddress): string | null | undefined {
if (address.port !== null) return parseValidPort(address.port);
return defaultPortForDirectScheme(address.scheme) ?? undefined;
}
/**
* Lenient split of a direct-connection address or URI into host, port, scheme, and credentials.
* Keeps invalid port text intact so callers can decide whether to carry it as text or reject it.
*/
export function parseDirectConnectionAddress(input: string): ParsedDirectConnectionAddress {
const trimmed = input.trim();
if (!trimmed) {
return {
scheme: null,
host: "",
port: null,
isIpv6: false,
path: "",
password: null,
sslParam: null,
};
}
const schemeMatch = SCHEME_PATTERN.exec(trimmed);
const scheme = schemeMatch ? (schemeMatch[1] ?? "").toLowerCase() : null;
const rest = schemeMatch ? trimmed.slice(schemeMatch[0].length) : trimmed;
const hashIndex = rest.indexOf("#");
const beforeHash = hashIndex === -1 ? rest : rest.slice(0, hashIndex);
const queryIndex = beforeHash.indexOf("?");
const beforeQuery = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
const query = new URLSearchParams(queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1));
const slashIndex = beforeQuery.indexOf("/");
const rawAuthority = slashIndex === -1 ? beforeQuery : beforeQuery.slice(0, slashIndex);
const path = slashIndex === -1 ? "" : beforeQuery.slice(slashIndex);
const { authority, password: userinfoPassword } = stripUserinfo(rawAuthority, scheme !== null);
const { host, port, isIpv6 } = splitAuthorityHostPort(authority);
return {
scheme,
host,
port,
isIpv6,
path,
password: query.get("password") || userinfoPassword || null,
sslParam: parseSslParam(query.get("ssl")),
};
}
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
export function isPairingLink(input: string): boolean {
const trimmed = input.trim();
return (
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
);
}
function shouldNormalizeBareHostPaste(
trimmed: string,
address: ParsedDirectConnectionAddress,
): boolean {
const hasOnlyTrailingSlashes = address.path.length > 0 && /^\/+$/.test(address.path);
if (address.path.length > 0 && !hasOnlyTrailingSlashes) return false;
return hasOnlyTrailingSlashes || (address.isIpv6 && trimmed.startsWith("["));
}
/**
* Extracts structured Direct connection form fields from a pasted `host:port`, bracketed IPv6,
* or supported URI (`http`, `https`, `ws`, `wss`, `tcp`). Returns `null` when the text is a plain
* host, bare IPv6, pairing link, unsupported scheme, or contains an invalid explicit port.
*/
export function parseDirectConnectionPaste(input: string): DirectConnectionPasteFields | null {
const trimmed = input.trim();
if (!trimmed || /[\r\n]/.test(trimmed) || isPairingLink(trimmed)) return null;
const address = parseDirectConnectionAddress(trimmed);
if (address.scheme !== null && !DIRECT_CONNECTION_SCHEMES.has(address.scheme)) return null;
if (hasInvalidPasteHost(address.host)) return null;
const port = resolvePastePort(address);
if (port === null) return null;
const useTls = resolveDirectSchemeTls(address.scheme, address.sslParam);
// A pasted `tcp://` URI is a complete Paseo connection string: omitting `?password=` means no
// password and clears any credential left over from a previous host.
const password =
address.scheme === "tcp" ? (address.password ?? "") : (address.password ?? undefined);
if (
port === undefined &&
useTls === undefined &&
password === undefined &&
!shouldNormalizeBareHostPaste(trimmed, address)
) {
return null;
}
return {
host: address.host,
...(port !== undefined ? { port } : {}),
...(useTls !== undefined ? { useTls } : {}),
...(password !== undefined ? { password } : {}),
};
}
export interface ResolvedDirectHostDraft {
host: string;
port: string;
isIpv6: boolean;
useTls: boolean;
password: string;
}
/**
* Resolves a Form draft where Host may still contain a manually typed `host:port` or URI.
* Honors explicit scheme, port, `ssl`, and `password` settings from Host while preserving
* separate form fields for anything Host did not specify.
*/
export function resolveDirectHostDraft(draft: DirectConnectionHostInput): ResolvedDirectHostDraft {
const address = parseDirectConnectionAddress(draft.host);
const explicitPort = address.port !== null && address.port.length > 0 ? address.port : null;
const port = (explicitPort ?? defaultPortForDirectScheme(address.scheme) ?? draft.port).trim();
let useTls = draft.useTls;
if (address.scheme === "https" || address.scheme === "wss") {
useTls = true;
} else if (address.scheme === "http" || address.scheme === "ws") {
useTls = false;
} else if (address.sslParam !== null) {
useTls = address.sslParam;
}
return {
host: address.host,
port,
isIpv6: address.isIpv6,
useTls,
password: address.password ?? draft.password,
};
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
/**
* Users often paste `host:port` or a full URL into the host field.
* Reduce it to a bare host (plus an optional port) before building the URI.
*/
export function normalizeDirectConnectionHost(input: string): NormalizedDirectConnectionHost {
const address = parseDirectConnectionAddress(input);
if (address.port !== null && !DIGITS_ONLY_PATTERN.test(address.port)) {
if (address.isIpv6 && address.port === "") {
return { host: address.host, port: null, isIpv6: true };
}
if (!address.isIpv6) {
return { host: `${address.host}:${address.port}`, port: null, isIpv6: false };
}
let host = input.trim().replace(SCHEME_PATTERN, "");
const suffixIndex = host.search(/[/?#]/);
if (suffixIndex !== -1) {
host = host.slice(0, suffixIndex);
}
return {
host: address.host,
port: address.port || null,
isIpv6: address.isIpv6,
};
const bracketed = BRACKETED_IPV6_PATTERN.exec(host);
if (bracketed) {
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true };
}
const hostWithPort = HOST_WITH_PORT_PATTERN.exec(host);
if (hostWithPort) {
return { host: hostWithPort[1] ?? "", port: hostWithPort[2] ?? null, isIpv6: false };
}
return { host, port: null, isIpv6: host.split(":").length > 2 };
}
export function buildDirectConnectionUri(
draft: DirectConnectionHostInput,
labels: DirectConnectionHostLabels,
): string {
const resolved = resolveDirectHostDraft(draft);
if (!resolved.host) {
const normalized = normalizeDirectConnectionHost(draft.host);
const port = Number((normalized.port ?? draft.port).trim());
if (!normalized.host) {
throw new Error(labels.hostRequired);
}
const port = parseValidPortNumber(resolved.port);
if (port === null) {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(labels.invalidPort);
}
return serializeConnectionUriForStorage({
host: resolved.host,
host: normalized.host,
port,
isIpv6: resolved.isIpv6,
useTls: resolved.useTls,
...(resolved.password ? { password: resolved.password } : {}),
isIpv6: normalized.isIpv6,
useTls: draft.useTls,
...(draft.password ? { password: draft.password } : {}),
});
}
@@ -1,16 +1,8 @@
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
import { PressHighlight } from "@/components/ui/press-highlight";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Alert,
Text,
View,
type LayoutChangeEvent,
type NativeSyntheticEvent,
type TextInputSelectionChangeEventData,
} from "react-native";
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { Check, Eye, EyeOff, Form, Link, Link2 } from "lucide-react-native";
@@ -35,14 +27,11 @@ import { useHardwareKeyboardPresent } from "@/keyboard/availability";
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -52,7 +41,6 @@ import {
type DirectConnectionMode,
type DirectConnectionUri,
type ResolvedDirectConnection,
type TextSelection,
} from "./direct-connection";
const FLEX_ONE_STYLE = { flex: 1 } as const;
@@ -480,22 +468,6 @@ interface FieldEvents {
onSubmit: () => void;
}
function syncTextField(
inputRef: React.RefObject<EditingTextInputHandle | null>,
selectionRef: React.RefObject<TextSelection | null> | null,
currentValue: string,
nextValue: string,
options: { collapseSelectionToEnd: boolean; forceReplace: boolean },
) {
if (!options.forceReplace && nextValue === currentValue) return;
const endSelection = { start: nextValue.length, end: nextValue.length };
inputRef.current?.replaceText(
nextValue,
options.collapseSelectionToEnd ? endSelection : undefined,
);
if (selectionRef) selectionRef.current = endSelection;
}
function DirectFormFields({
input,
isSaving,
@@ -509,13 +481,6 @@ function DirectFormFields({
}) {
const { t } = useTranslation();
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const hostInputRef = useRef<EditingTextInputHandle | null>(null);
const portInputRef = useRef<EditingTextInputHandle | null>(null);
const passwordInputRef = useRef<EditingTextInputHandle | null>(null);
const sslToggleRef = useRef<View | null>(null);
const hostSelectionRef = useRef<TextSelection | null>(null);
const portSelectionRef = useRef<TextSelection | null>(null);
const suppressedPasteRef = useRef<{ field: "host" | "port"; text: string } | null>(null);
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
@@ -528,188 +493,22 @@ function DirectFormFields({
[isSaving, input.useTls],
);
const syncFormInputs = useCallback(
(
previous: DirectConnectionForm,
next: DirectConnectionForm,
source:
| { kind: "paste"; field: "host" | "port" }
| { kind: "change"; field: "host" | "port" | "password"; rawText: string }
| { kind: "sync" },
) => {
syncTextField(
hostInputRef,
hostSelectionRef,
source.kind === "change" && source.field === "host" ? source.rawText : previous.host,
next.host,
{
collapseSelectionToEnd: source.kind !== "sync" && source.field === "host",
forceReplace: source.kind === "paste" && source.field === "host",
},
);
syncTextField(
portInputRef,
portSelectionRef,
source.kind === "change" && source.field === "port" ? source.rawText : previous.port,
next.port,
{
collapseSelectionToEnd: source.kind !== "sync" && source.field === "port",
forceReplace: source.kind === "paste" && source.field === "port",
},
);
syncTextField(
passwordInputRef,
null,
source.kind === "change" && source.field === "password"
? source.rawText
: previous.password,
next.password,
{ collapseSelectionToEnd: false, forceReplace: false },
);
},
[],
);
const handleNativePaste = useEffectEvent(
(field: "host" | "port", inputEl: HTMLInputElement, event: ClipboardEvent) => {
if (isSaving) return;
const pastedText = event.clipboardData?.getData("text/plain");
if (!pastedText) return;
const value = inputEl.value;
const selectionStart = inputEl.selectionStart ?? value.length;
const selectionEnd = inputEl.selectionEnd ?? value.length;
const replacesWholeField = selectionStart === 0 && selectionEnd === value.length;
if (!replacesWholeField) {
// Record the resulting single-line input value so the immediately following onChangeText
// treats a partial/mid-field paste as a literal edit rather than smart-filling the form.
const singleLinePaste = pastedText.replace(/[\r\n]/g, "");
suppressedPasteRef.current = {
field,
text: value.slice(0, selectionStart) + singleLinePaste + value.slice(selectionEnd),
};
return;
}
const next = pasteDirectConnection(input, pastedText);
if (!next) return;
event.preventDefault();
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "paste", field });
}
onChange(next);
},
);
useEffect(() => {
if (!isWeb) return;
const entries: Array<{ field: "host" | "port"; handle: EditingTextInputHandle | null }> = [
{ field: "host", handle: hostInputRef.current },
{ field: "port", handle: portInputRef.current },
];
const cleanups: Array<() => void> = [];
for (const { field, handle } of entries) {
const nativeEl = handle?.getNativeRef();
if (!(nativeEl instanceof HTMLInputElement)) continue;
const listener = (event: ClipboardEvent) => handleNativePaste(field, nativeEl, event);
nativeEl.addEventListener("paste", listener);
cleanups.push(() => nativeEl.removeEventListener("paste", listener));
}
return () => {
for (const cleanup of cleanups) cleanup();
};
}, []);
const handleHostSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
hostSelectionRef.current = event.nativeEvent.selection;
},
[],
);
const handlePortSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
portSelectionRef.current = event.nativeEvent.selection;
},
[],
);
const handleHostBlur = useCallback(
(event: unknown) => {
fieldEvents.onBlur();
// Clicking Use SSL on web blurs Host before onPress fires. Defer committing to the checkbox
// handler so blur's scheme inference cannot flip Use SSL right before the click toggles it.
if (isWeb && sslToggleRef.current instanceof Node) {
const relatedTarget =
(event as { relatedTarget?: unknown; nativeEvent?: { relatedTarget?: unknown } } | null)
?.relatedTarget ??
(event as { nativeEvent?: { relatedTarget?: unknown } } | null)?.nativeEvent
?.relatedTarget;
if (relatedTarget instanceof Node && sslToggleRef.current.contains(relatedTarget)) {
return;
}
}
const next = commitHost(input);
if (next === input) return;
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
},
[fieldEvents, input, onChange, syncFormInputs],
);
const handleHostChange = useCallback(
(host: string) => {
const suppressed = suppressedPasteRef.current;
suppressedPasteRef.current = null;
const allowSmartPaste = !(suppressed?.field === "host" && suppressed.text === host);
const next = editHost(input, host, {
allowSmartPaste,
selection: hostSelectionRef.current,
});
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "host", rawText: host });
}
onChange(next);
},
[input, onChange, syncFormInputs],
(host: string) => onChange(editHost(input, host)),
[input, onChange],
);
const handlePortChange = useCallback(
(port: string) => {
const suppressed = suppressedPasteRef.current;
suppressedPasteRef.current = null;
const allowSmartPaste = !(suppressed?.field === "port" && suppressed.text === port);
const next = editPort(input, port, {
allowSmartPaste,
selection: portSelectionRef.current,
});
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "port", rawText: port });
}
onChange(next);
},
[input, onChange, syncFormInputs],
(port: string) => onChange(editForm(input, { port })),
[input, onChange],
);
const handlePasswordChange = useCallback(
(password: string) => {
const next = editForm(input, { password });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "password", rawText: password });
}
onChange(next);
},
[input, onChange, syncFormInputs],
(password: string) => onChange(editForm(input, { password })),
[input, onChange],
);
const handleToggleUseTls = useCallback(() => {
if (isSaving) return;
const next = editForm(input, { useTls: !input.useTls });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
}, [input, isSaving, onChange, syncFormInputs]);
onChange(editForm(input, { useTls: !input.useTls }));
}, [input, isSaving, onChange]);
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
const handleTogglePasswordVisibility = useCallback(() => {
setIsPasswordVisible((current) => !current);
@@ -723,15 +522,13 @@ function DirectFormFields({
<View style={hostFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
<AdaptiveTextInput
ref={hostInputRef}
testID="direct-host-input"
nativeID="direct-host-input"
accessibilityLabel={t("pairing.direct.fields.host")}
initialValue={input.host}
onChangeText={handleHostChange}
onSelectionChange={handleHostSelectionChange}
onFocus={fieldEvents.onFocus}
onBlur={handleHostBlur}
onBlur={fieldEvents.onBlur}
autoFocus={fieldEvents.autoFocus}
placeholder="localhost"
style={styles.input}
@@ -745,13 +542,11 @@ function DirectFormFields({
<View style={portFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
<AdaptiveTextInput
ref={portInputRef}
testID="direct-port-input"
nativeID="direct-port-input"
accessibilityLabel={t("pairing.direct.fields.port")}
initialValue={input.port}
onChangeText={handlePortChange}
onSelectionChange={handlePortSelectionChange}
onFocus={fieldEvents.onFocus}
onBlur={fieldEvents.onBlur}
placeholder="6767"
@@ -767,7 +562,6 @@ function DirectFormFields({
</View>
<PressHighlight
ref={sslToggleRef}
style={styles.checkboxRow}
onPress={handleToggleUseTls}
disabled={isSaving}
@@ -792,7 +586,6 @@ function DirectFormFields({
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
<View style={styles.passwordRow}>
<AdaptiveTextInput
ref={passwordInputRef}
testID="direct-password-input"
nativeID="direct-password-input"
accessibilityLabel={t("pairing.direct.fields.password")}
@@ -1,14 +1,11 @@
import { describe, expect, it } from "vitest";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -31,17 +28,7 @@ const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
const { host = "", ...rest } = fields;
return editForm(typeHost(openDirectConnection(), host), rest);
}
function typeHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
let current = input;
let value = current.mode === "form" ? current.host : "";
for (const ch of text) {
value += ch;
current = editHost(current, value);
}
return current;
return editForm(editHost(openDirectConnection(), host), rest);
}
function uri(text: string): DirectConnectionInput {
@@ -142,20 +129,6 @@ describe("switching from URI to Form", () => {
port: "7000",
useTls: true,
});
expect(switchMode(uri("https://myhost.ts.net"), "form")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(switchMode(uri("wss://myhost.ts.net:7443/ws"), "form")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "7443",
useTls: true,
password: "",
});
});
it("round-trips any form with a host", () => {
@@ -180,348 +153,18 @@ describe("switching from URI to Form", () => {
});
describe("typing in Host", () => {
it("never hijacks manual character-by-character typing for host:port, URLs, or bare IPv6", () => {
for (const text of [
"host:7000",
"http://host:7000/",
"[::1]:7000",
"::1",
"2001:1234::1",
"fe80::1",
"tcp://h:7000?password=x",
]) {
expect(typeHost(openDirectConnection(), text)).toEqual({
mode: "form",
host: text,
port: "6767",
useTls: false,
password: "",
});
it("keeps host:port and URL shapes in Host", () => {
for (const text of ["host:7000", "http://host:7000/", "[::1]:7000"]) {
expect(editHost(openDirectConnection(), text)).toMatchObject({ mode: "form", host: text });
}
});
it("does not trigger smart-fill on backspace or mid-string paste", () => {
const typedIpv6 = typeHost(openDirectConnection(), "2001:1234:");
expect(editHost(typedIpv6, "2001:1234")).toEqual({
mode: "form",
host: "2001:1234",
port: "6767",
useTls: false,
password: "",
});
const typedUrl = typeHost(openDirectConnection(), "http://example.com");
expect(editHost(typedUrl, "http://sub.example.com")).toEqual({
mode: "form",
host: "http://sub.example.com",
port: "6767",
useTls: false,
password: "",
});
const typedHostPort = typeHost(openDirectConnection(), "example.com:6768");
expect(editHost(typedHostPort, "my-example.com:6768")).toEqual({
mode: "form",
host: "my-example.com:6768",
port: "6767",
useTls: false,
password: "",
});
});
it("smart-fills Host, Port, Use SSL, and Password on paste into Host", () => {
expect(editHost(openDirectConnection(), "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "100.91.42.18:6767")).toEqual({
mode: "form",
host: "100.91.42.18",
port: "6767",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "hetzner.tail8a2f.ts.net:6768")).toEqual({
mode: "form",
host: "hetzner.tail8a2f.ts.net",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "[::1]:6768")).toEqual({
mode: "form",
host: "::1",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "https://myhost.ts.net:6767/")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "6767",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "https://myhost.ts.net")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "http://myhost.ts.net")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "80",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "wss://myhost.ts.net/ws")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "tcp://h:7000?ssl=true&password=x")).toEqual({
mode: "form",
host: "h",
port: "7000",
useTls: true,
password: "x",
});
});
it("preserves unspecified fields and updates specified fields on paste", () => {
const existing = form({
host: "oldhost",
port: "7000",
useTls: true,
password: "saved-password",
});
// host:port without scheme or password preserves SSL and password
expect(pasteDirectConnection(existing, "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: true,
password: "saved-password",
});
// http:// explicitly disables SSL while keeping password
expect(pasteDirectConnection(existing, "http://localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "saved-password",
});
// tcp:// without port or password keeps current port, clears stale password, and sets SSL from ?ssl=
expect(pasteDirectConnection(existing, "tcp://newhost")).toEqual({
mode: "form",
host: "newhost",
port: "7000",
useTls: false,
password: "",
});
// tcp:// with port and no password clears the previous host's password
expect(pasteDirectConnection(existing, "tcp://second.example.test:7443")).toEqual({
mode: "form",
host: "second.example.test",
port: "7443",
useTls: false,
password: "",
});
// tcp:// with password overwrites password
expect(pasteDirectConnection(existing, "tcp://newhost:8080?ssl=true&password=next")).toEqual({
mode: "form",
host: "newhost",
port: "8080",
useTls: true,
password: "next",
});
});
it("uses native selection range to distinguish full replacements from partial pastes", () => {
const existingDomain = form({ host: "home.example.test", port: "6767" });
expect(
editHost(existingDomain, "https://new.example.test", {
selection: { start: 0, end: "home.example.test".length },
}),
).toEqual({
mode: "form",
host: "new.example.test",
port: "443",
useTls: true,
password: "",
});
// Replacing only a leading word slice is a partial edit, not a full paste
expect(
editHost(existingDomain, "https://new.example.test", {
selection: { start: 0, end: 4 },
}),
).toEqual({
mode: "form",
host: "https://new.example.test",
port: "6767",
useTls: false,
password: "",
});
const existingIp = form({ host: "192.168.1.10", port: "6767" });
expect(
editHost(existingIp, "192.168.1.11:6710", {
selection: { start: 0, end: "192.168.1.10".length },
}),
).toEqual({
mode: "form",
host: "192.168.1.11",
port: "6710",
useTls: false,
password: "",
});
// Pasting `:6710` at the end of an existing host stays a literal edit
expect(
editHost(existingIp, "192.168.1.10:6710", {
selection: { start: "192.168.1.10".length, end: "192.168.1.10".length },
}),
).toEqual({
mode: "form",
host: "192.168.1.10:6710",
port: "6767",
useTls: false,
password: "",
});
});
it("preserves SSL, port, and password when submitting or switching a manually typed URI", () => {
const typedTcp = typeHost(
openDirectConnection(),
"tcp://secure.example.test:7443?ssl=true&password=example",
);
expect(resolveConnection(typedTcp, LABELS)).toEqual({
kind: "direct",
uri: "tcp://secure.example.test:7443?ssl=true",
endpoint: "secure.example.test:7443",
useTls: true,
password: "example",
});
expect(switchMode(typedTcp, "uri")).toMatchObject({
it("moves a typed or pasted URI to URI mode", () => {
expect(editHost(openDirectConnection(), "tcp://h:7000?password=x")).toEqual({
mode: "uri",
uri: "tcp://secure.example.test:7443?ssl=true&password=example",
uri: "tcp://h:7000?password=x",
prompt: null,
});
const typedHttps = typeHost(openDirectConnection(), "https://myhost.ts.net");
expect(resolveConnection(typedHttps, LABELS)).toEqual({
kind: "direct",
uri: "tcp://myhost.ts.net:443?ssl=true",
endpoint: "myhost.ts.net:443",
useTls: true,
});
expect(switchMode(typedHttps, "uri")).toMatchObject({
mode: "uri",
uri: "tcp://myhost.ts.net:443?ssl=true",
});
// Typing a tcp:// URI without SSL or password clears a previous host's SSL and password
const previousHost = form({
host: "first.example.test",
port: "6767",
useTls: true,
password: "first-password",
});
const replacedByTyping = typeHost(editHost(previousHost, ""), "tcp://second.example.test:7443");
expect(commitHost(replacedByTyping)).toEqual({
mode: "form",
host: "second.example.test",
port: "7443",
useTls: false,
password: "",
});
expect(resolveConnection(replacedByTyping, LABELS)).toEqual({
kind: "direct",
uri: "tcp://second.example.test:7443",
endpoint: "second.example.test:7443",
useTls: false,
});
// Editing Password after typing a URI with a wrong password overrides the URI password
const typedWrongPassword = typeHost(
openDirectConnection(),
"tcp://host.example.test:7000?password=wrong",
);
const corrected = editForm(typedWrongPassword, { password: "right" });
expect(corrected).toEqual({
mode: "form",
host: "host.example.test",
port: "7000",
useTls: false,
password: "right",
});
expect(resolveConnection(corrected, LABELS)).toEqual({
kind: "direct",
uri: "tcp://host.example.test:7000",
endpoint: "host.example.test:7000",
useTls: false,
password: "right",
});
});
it("smart-fills when replacing an existing host or pasting into Port", () => {
const withHost = form({ host: "localhost", port: "6767" });
expect(editHost(withHost, "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "",
});
expect(editPort(openDirectConnection(), "100.91.42.18:6767")).toEqual({
mode: "form",
host: "100.91.42.18",
port: "6767",
useTls: false,
password: "",
});
expect(editPort(openDirectConnection(), "https://myhost.ts.net:7443")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "7443",
useTls: true,
password: "",
});
expect(editPort(openDirectConnection(), "7000")).toEqual({
mode: "form",
host: "",
port: "7000",
useTls: false,
password: "",
});
});
it("leaves invalid ports and bare IPv6 untouched on paste", () => {
expect(pasteDirectConnection(openDirectConnection(), "localhost:70000")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "localhost:0")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "localhost:abc")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "::1")).toBeNull();
expect(editHost(openDirectConnection(), "localhost:70000")).toMatchObject({
mode: "form",
host: "localhost:70000",
port: "6767",
});
});
it("moves a pasted pairing link to URI mode", () => {
expect(editHost(openDirectConnection(), RELAY_LINK)).toMatchObject({
mode: "uri",
uri: RELAY_LINK,
@@ -534,11 +177,6 @@ describe("typing in Host", () => {
uri: OFFER_LINK,
prompt: null,
});
expect(pasteDirectConnection(openDirectConnection(), OFFER_LINK)).toEqual({
mode: "uri",
uri: OFFER_LINK,
prompt: null,
});
});
});
@@ -1,11 +1,6 @@
import {
buildDirectConnectionUri,
defaultPortForDirectScheme,
isPairingLink,
parseDirectConnectionAddress,
parseDirectConnectionPaste,
resolveDirectHostDraft,
resolveDirectSchemeTls,
normalizeDirectConnectionHost,
type DirectConnectionHostLabels,
} from "@/components/direct-connection-host";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
@@ -43,6 +38,7 @@ export type ResolvedDirectConnection =
| { kind: "relay"; link: string; password?: string };
const DEFAULT_PORT = "6767";
const TCP_URI_PATTERN = /^tcp:\/\//i;
export function openDirectConnection(): DirectConnectionForm {
return { mode: "form", host: "", port: DEFAULT_PORT, useTls: false, password: "" };
@@ -63,97 +59,21 @@ export function canSwitchToForm(input: DirectConnectionInput): boolean {
return input.mode === "form" || !isPairingLink(input.uri);
}
/**
* Commits a manually typed `host:port`, URI, or pairing link sitting in Host into the form's
* structured fields (or URI mode for pairing links) once the user leaves Host or submits.
*/
export function commitHost(input: DirectConnectionInput): DirectConnectionInput {
if (input.mode !== "form") return input;
return pasteDirectConnection(input, input.host) ?? input;
}
function commitDirectFormHost(input: DirectConnectionForm): DirectConnectionForm {
const committed = pasteDirectConnection(input, input.host);
return committed && committed.mode === "form" ? committed : input;
}
export function editForm(
input: DirectConnectionInput,
fields: Partial<Omit<DirectConnectionForm, "mode" | "host">>,
): DirectConnectionInput {
if (input.mode !== "form") return input;
return { ...commitDirectFormHost(input), ...fields };
return { ...input, ...fields };
}
/**
* Parses a pasted host:port, URI, or pairing link into the next Direct connection state.
* Returns `null` when the text should stay a literal edit in the active field.
*/
export function pasteDirectConnection(
input: DirectConnectionInput,
text: string,
): DirectConnectionInput | null {
if (input.mode !== "form") return null;
if (isPairingLink(text)) return { mode: "uri", uri: text.trim(), prompt: null };
const parsed = parseDirectConnectionPaste(text);
if (!parsed) return null;
return {
...input,
host: parsed.host,
...(parsed.port !== undefined ? { port: parsed.port } : {}),
...(parsed.useTls !== undefined ? { useTls: parsed.useTls } : {}),
...(parsed.password !== undefined ? { password: parsed.password } : {}),
};
}
export interface TextSelection {
start: number;
end: number;
}
export interface DirectFieldEditOptions {
allowSmartPaste?: boolean;
/** The input's selection range immediately before this text change, when known. */
selection?: TextSelection | null;
}
/**
* Updates Host in Form mode. Multi-character pastes that look like a host:port, URI, or pairing
* link populate the form (or switch to URI mode for pairing links) without fighting normal typing.
*/
export function editHost(
input: DirectConnectionInput,
text: string,
options?: DirectFieldEditOptions,
): DirectConnectionInput {
/** A URI typed or pasted into Host moves to URI mode, where its query and pairing data count. */
export function editHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
if (input.mode !== "form") return input;
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.host, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
return { ...input, host: text };
}
/** Updates Port in Form mode, smart-filling when a full host:port or URI is pasted into Port. */
export function editPort(
input: DirectConnectionInput,
text: string,
options?: DirectFieldEditOptions,
): DirectConnectionInput {
if (input.mode !== "form") return input;
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.port, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
return { ...commitDirectFormHost(input), port: text };
}
/** Editing the URI to point at another host drops the password typed for the previous one. */
export function editUri(input: DirectConnectionInput, text: string): DirectConnectionInput {
if (input.mode !== "uri") return input;
@@ -180,12 +100,11 @@ export function resolveConnection(
input: DirectConnectionInput,
labels: DirectConnectionHostLabels,
): ResolvedDirectConnection {
const effective = commitHost(input);
if (effective.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(effective, labels));
if (input.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(input, labels));
}
const uri = effective.uri.trim();
const promptPassword = effective.prompt?.password || undefined;
const uri = input.uri.trim();
const promptPassword = input.prompt?.password || undefined;
if (isPairingLink(uri)) {
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
}
@@ -204,85 +123,43 @@ function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectCo
};
}
function hasAddressDelimiter(text: string): boolean {
return isPairingLink(text) || /[:[\]/]/.test(text);
}
function matchesSelectionEdit(previous: string, next: string, selection: TextSelection): boolean {
const start = Math.min(selection.start, selection.end);
const end = Math.max(selection.start, selection.end);
const prefix = previous.slice(0, start);
const suffix = previous.slice(end);
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
function isPairingLink(uri: string): boolean {
const trimmed = uri.trim();
return (
next.length >= prefix.length + suffix.length && next.startsWith(prefix) && next.endsWith(suffix)
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
);
}
function isWholeFieldPasteChange(
previous: string,
next: string,
selection?: TextSelection | null,
): boolean {
if (next === previous) return false;
if (previous.length === 0) return next.length >= 2 && hasAddressDelimiter(next);
if (selection) {
const start = Math.min(selection.start, selection.end);
const end = Math.max(selection.start, selection.end);
if (start === 0 && end === previous.length) {
return next.length >= 2 && hasAddressDelimiter(next);
}
if (matchesSelectionEdit(previous, next, selection)) {
return false;
}
}
let prefix = 0;
const minLength = Math.min(previous.length, next.length);
while (prefix < minLength && previous[prefix] === next[prefix]) {
prefix += 1;
}
let suffix = 0;
while (
suffix < minLength - prefix &&
previous[previous.length - 1 - suffix] === next[next.length - 1 - suffix]
) {
suffix += 1;
}
const inserted = next.slice(prefix, next.length - suffix);
if (inserted.length < 2) return false;
if (prefix > 0 && suffix > 0) return false;
return isPairingLink(next) || /[:[\]/]/.test(inserted);
function looksLikeUri(text: string): boolean {
return TCP_URI_PATTERN.test(text.trim()) || isPairingLink(text);
}
// Built as text, not through the strict serializer, so an invalid port carries over and Connect
// reports it instead of the switch failing.
function formToUri(input: DirectConnectionForm): string {
const committed = commitHost(input);
if (committed.mode === "uri") return committed.uri;
const resolved = resolveDirectHostDraft(committed);
if (!resolved.host) return "";
const host = resolved.isIpv6 ? `[${resolved.host}]` : resolved.host;
const normalized = normalizeDirectConnectionHost(input.host);
if (!normalized.host) return "";
const host = normalized.isIpv6 ? `[${normalized.host}]` : normalized.host;
const port = normalized.port ?? input.port.trim();
const query = new URLSearchParams();
if (resolved.useTls) query.set("ssl", "true");
if (resolved.password) query.set("password", resolved.password);
if (input.useTls) query.set("ssl", "true");
if (input.password) query.set("password", input.password);
const search = query.toString();
return `tcp://${host}:${resolved.port}${search ? `?${search}` : ""}`;
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
}
function uriToForm(uri: string): DirectConnectionForm {
const address = parseDirectConnectionAddress(uri);
const address = splitUri(uri);
if (!address.host) return openDirectConnection();
const port =
(address.port && address.port.length > 0 ? address.port : null) ??
defaultPortForDirectScheme(address.scheme) ??
DEFAULT_PORT;
return {
mode: "form",
host: address.host,
port,
useTls: resolveDirectSchemeTls(address.scheme, address.sslParam) ?? false,
password: address.password ?? "",
port: address.port ?? DEFAULT_PORT,
useTls: address.query.get("ssl") === "true",
password: address.query.get("password") ?? "",
};
}
@@ -297,7 +174,35 @@ export function uriHostLabel(uri: string): string | null {
return null;
}
}
const address = parseDirectConnectionAddress(trimmed);
const address = splitUri(trimmed);
if (!address.host || !address.port) return null;
return address.isIpv6 ? `[${address.host}]:${address.port}` : `${address.host}:${address.port}`;
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
/** Lenient split of a typed URI. Keeps an invalid port as text instead of rejecting it. */
function splitUri(uri: string): {
host: string;
port: string | null;
isIpv6: boolean;
query: URLSearchParams;
} {
const rest = uri.trim().replace(SCHEME_PATTERN, "");
const queryIndex = rest.indexOf("?");
const query = new URLSearchParams(
queryIndex === -1 ? "" : rest.slice(queryIndex + 1).split("#")[0],
);
const authority = rest.split(/[/?#]/)[0] ?? "";
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
if (bracketed) {
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true, query };
}
const parts = authority.split(":");
if (parts.length === 2) {
return { host: parts[0] ?? "", port: parts[1] || null, isIpv6: false, query };
}
return { host: authority, port: null, isIpv6: parts.length > 2, query };
}
+207 -8
View File
@@ -12,7 +12,13 @@ import {
type TransportMessage,
} from "./encrypted-channel.js";
import { exportPublicKey, generateKeyPair } from "./crypto.js";
import { MAX_CHUNK_DATA_BYTES } from "./protected-records.js";
import { createNoiseInitiator } from "./noise/index.js";
import {
decodeProtectedRecord,
encodeProtectedRecord,
MAX_CHUNK_DATA_BYTES,
protectedRecordByteLength,
} from "./protected-records.js";
interface Frame {
data: string | ArrayBuffer;
@@ -159,16 +165,209 @@ describe("secure channel: protected mode", () => {
expect(new Uint8Array(pair.clientReceived[1] as ArrayBuffer)).toEqual(new Uint8Array(bytes(7)));
});
it("keeps text as base64 text frames and binary as binary frames when negotiated", async () => {
it("sends both text and binary records as binary frames without base64 overhead when negotiated", async () => {
const pair = await openProtectedPair();
pair.link.recordedToDaemon.length = 0;
await pair.client.send("text");
await pair.client.send(bytes(3));
pair.link.recordedToClient.length = 0;
const jsonText = JSON.stringify({
type: "session",
message: { text: "héllo ".repeat(200) },
});
const textBytes = new TextEncoder().encode(jsonText).byteLength;
const expectedTextWireBytes = protectedRecordByteLength(textBytes);
const legacyBase64WireBytes = 4 * Math.ceil(expectedTextWireBytes / 3);
const binaryPayload = bytes(3);
const expectedBinaryWireBytes = protectedRecordByteLength(binaryPayload.byteLength);
await pair.client.send(jsonText);
await pair.client.send(binaryPayload);
await pair.daemon.send(jsonText);
await pair.daemon.send(binaryPayload);
await settle();
expect(pair.link.recordedToDaemon.map((frame) => frame.isBinary)).toEqual([false, true]);
expect(pair.link.recordedToDaemon[0].data).not.toContain("text");
expect(pair.client.outboundWireByteLength(bytes(3))).toBe(3 + 2 + 6 + 16);
expect(pair.client.outboundWireByteLength("text")).toBe(4 * Math.ceil((4 + 24) / 3));
expect(pair.link.recordedToDaemon.map((frame) => frame.isBinary)).toEqual([true, true]);
expect(pair.link.recordedToClient.map((frame) => frame.isBinary)).toEqual([true, true]);
const clientTextWire = pair.link.recordedToDaemon[0].data as ArrayBuffer;
const daemonTextWire = pair.link.recordedToClient[0].data as ArrayBuffer;
expect(clientTextWire).toBeInstanceOf(ArrayBuffer);
expect(daemonTextWire).toBeInstanceOf(ArrayBuffer);
expect(clientTextWire.byteLength).toBe(expectedTextWireBytes);
expect(daemonTextWire.byteLength).toBe(expectedTextWireBytes);
expect(clientTextWire.byteLength).toBeLessThan(legacyBase64WireBytes * 0.76);
expect(Buffer.from(clientTextWire).toString("utf8")).not.toContain("héllo");
expect(pair.client.outboundWireByteLength(jsonText)).toBe(expectedTextWireBytes);
expect(pair.daemon.outboundWireByteLength(jsonText)).toBe(expectedTextWireBytes);
expect(pair.client.outboundWireByteLength(binaryPayload)).toBe(expectedBinaryWireBytes);
expect(pair.daemon.outboundWireByteLength(binaryPayload)).toBe(expectedBinaryWireBytes);
expect(pair.daemonReceived[0]).toBe(jsonText);
expect(new Uint8Array(pair.daemonReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(binaryPayload),
);
expect(pair.clientReceived[0]).toBe(jsonText);
expect(new Uint8Array(pair.clientReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(binaryPayload),
);
});
it("interoperates with older peers sending base64 text frames in both directions", async () => {
const toBase64TextFrame = (frame: Frame): Frame => {
if (!frame.isBinary) return frame;
return {
data: Buffer.from(frame.data as ArrayBuffer).toString("base64"),
isBinary: false,
};
};
// Old client (base64 text frames for text, binary for binary) <-> New daemon (binary for both).
const oldClientPair = await openProtectedPair();
oldClientPair.link.recordedToDaemon.length = 0;
oldClientPair.link.recordedToClient.length = 0;
let clientSentCount = 0;
oldClientPair.link.setToDaemon((frame) => {
clientSentCount += 1;
// Convert text frames (#1 and #3) to v0.13-v0.19 base64 text wire format; keep binary (#2) binary.
return clientSentCount === 2 ? frame : toBase64TextFrame(frame);
});
const largeText = "a".repeat(MAX_CHUNK_DATA_BYTES + 123);
await oldClientPair.client.send("from old client");
await oldClientPair.client.send(bytes(9));
await oldClientPair.client.send(largeText);
await oldClientPair.daemon.send("from new daemon");
await oldClientPair.daemon.send(bytes(11));
await settle(100);
expect(oldClientPair.link.recordedToClient.map((f) => f.isBinary)).toEqual([true, true]);
expect(oldClientPair.daemonReceived[0]).toBe("from old client");
expect(new Uint8Array(oldClientPair.daemonReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(9)),
);
expect(oldClientPair.daemonReceived[2]).toBe(largeText);
expect(oldClientPair.clientReceived[0]).toBe("from new daemon");
expect(new Uint8Array(oldClientPair.clientReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(11)),
);
// New client (binary for both) <-> Old daemon (base64 text frames for text, binary for binary).
const oldDaemonPair = await openProtectedPair();
oldDaemonPair.link.recordedToDaemon.length = 0;
oldDaemonPair.link.recordedToClient.length = 0;
let daemonSentCount = 0;
oldDaemonPair.link.setToClient((frame) => {
daemonSentCount += 1;
return daemonSentCount === 2 ? frame : toBase64TextFrame(frame);
});
await oldDaemonPair.client.send("from new client");
await oldDaemonPair.client.send(bytes(6));
await oldDaemonPair.daemon.send("from old daemon");
await oldDaemonPair.daemon.send(bytes(8));
await oldDaemonPair.daemon.send(largeText);
await settle(100);
expect(oldDaemonPair.link.recordedToDaemon.map((f) => f.isBinary)).toEqual([true, true]);
expect(oldDaemonPair.daemonReceived[0]).toBe("from new client");
expect(new Uint8Array(oldDaemonPair.daemonReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(6)),
);
expect(oldDaemonPair.clientReceived[0]).toBe("from old daemon");
expect(new Uint8Array(oldDaemonPair.clientReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(8)),
);
expect(oldDaemonPair.clientReceived[2]).toBe(largeText);
});
it("falls back to base64 text frames when a peer negotiates binaryCiphertext=false", async () => {
const link = createLink();
const daemonKeyPair = generateKeyPair();
const daemonReceived: Array<string | ArrayBuffer> = [];
const daemonPromise = openDaemonSecureChannel(link.daemon, {
daemonKeyPair,
events: { onmessage: (data) => daemonReceived.push(data) },
});
const prologue = new TextEncoder().encode("paseo-relay-e2ee/1");
const initiator = createNoiseInitiator({
remoteStatic: daemonKeyPair.publicKey,
prologue,
});
const msg1 = initiator.writeMessage(new Uint8Array([0x01, 0x00]));
const legacyKeyPair = generateKeyPair();
const hello = JSON.stringify({
type: "e2ee_hello",
key: exportPublicKey(legacyKeyPair.publicKey),
protected: { v: 1, message: Buffer.from(msg1).toString("base64") },
});
const readyPromise = new Promise<string>((resolve) => {
Object.assign(link.client, {
onmessage: (message: TransportMessage) => {
if (!message.isBinary && typeof message.data === "string") {
resolve(message.data);
}
},
});
});
link.client.send(hello);
const readyText = await readyPromise;
const daemon = await daemonPromise;
const ready = JSON.parse(readyText) as { protected: { v: number; message: string } };
const selectedPayload = initiator.readMessage(
new Uint8Array(Buffer.from(ready.protected.message, "base64")),
);
expect(selectedPayload).toEqual(new Uint8Array([0x01, 0x00]));
const { send: clientSend, receive: clientReceive } = initiator.split();
const daemonWireFrames: Frame[] = [];
Object.assign(link.client, {
onmessage: (message: TransportMessage) => {
daemonWireFrames.push({ data: message.data, isBinary: message.isBinary });
},
});
const textPayload = "base64 fallback text";
const binaryPayload = bytes(5);
await daemon.send(textPayload);
await daemon.send(binaryPayload);
await settle();
expect(daemonWireFrames.map((f) => f.isBinary)).toEqual([false, false]);
expect(daemon.outboundWireByteLength(textPayload)).toBe(
4 *
Math.ceil(protectedRecordByteLength(new TextEncoder().encode(textPayload).byteLength) / 3),
);
expect(daemon.outboundWireByteLength(binaryPayload)).toBe(
4 * Math.ceil(protectedRecordByteLength(binaryPayload.byteLength) / 3),
);
const decodedText = decodeProtectedRecord(
new Uint8Array(Buffer.from(daemonWireFrames[0].data as string, "base64")),
clientReceive,
);
expect(decodedText.kind).toBe("text");
expect(new TextDecoder().decode(decodedText.data)).toBe(textPayload);
const decodedBinary = decodeProtectedRecord(
new Uint8Array(Buffer.from(daemonWireFrames[1].data as string, "base64")),
clientReceive,
);
expect(decodedBinary.kind).toBe("binary");
expect(decodedBinary.data).toEqual(new Uint8Array(binaryPayload));
// Daemon still accepts base64-encoded records from the client.
const clientRecord = encodeProtectedRecord(
"text",
new TextEncoder().encode("client fallback"),
clientSend,
);
link.client.send(Buffer.from(clientRecord).toString("base64"));
await settle();
expect(daemonReceived).toEqual(["client fallback"]);
});
it("carries frames larger than one Noise message", async () => {
+2 -2
View File
@@ -653,7 +653,7 @@ class ProtectedChannel implements InnerChannel {
this.fail(this.role.failureCloseCode, err.message);
throw err;
}
if (this.params.binaryCiphertext && kind === "binary") {
if (this.params.binaryCiphertext) {
await this.transport.send(toArrayBuffer(wire));
return;
}
@@ -663,7 +663,7 @@ class ProtectedChannel implements InnerChannel {
outboundWireByteLength(data: string | ArrayBuffer): number {
const plaintextBytes = typeof data === "string" ? utf8ByteLength(data) : data.byteLength;
const wireBytes = protectedRecordByteLength(plaintextBytes);
if (this.params.binaryCiphertext && typeof data !== "string") return wireBytes;
if (this.params.binaryCiphertext) return wireBytes;
return 4 * Math.ceil(wireBytes / 3);
}
@@ -114,6 +114,9 @@ async function openUpdatedRelayClient(args: {
channel: SecureChannel;
serverInfo: { features?: Record<string, unknown> };
messages: unknown[];
wireOutbound: Array<{ isBinary: boolean; byteLength: number }>;
wireInbound: Array<{ isBinary: boolean; text: string | null }>;
retryHello: () => void;
waitFor: (predicate: (message: unknown) => boolean) => Promise<unknown>;
close: () => void;
}> {
@@ -125,8 +128,18 @@ async function openUpdatedRelayClient(args: {
role: "client",
}),
);
const wireOutbound: Array<{ isBinary: boolean; byteLength: number }> = [];
const wireInbound: Array<{ isBinary: boolean; text: string | null }> = [];
let helloText: string | undefined;
const transport: Transport = {
send: (data) => ws.send(data),
send: (data) => {
if (typeof data === "string") helloText ??= data;
wireOutbound.push({
isBinary: typeof data !== "string",
byteLength: typeof data === "string" ? Buffer.byteLength(data, "utf8") : data.byteLength,
});
ws.send(data);
},
close: (code?: number, reason?: string) => ws.close(code, reason),
onmessage: null,
onclose: null,
@@ -134,10 +147,10 @@ async function openUpdatedRelayClient(args: {
};
ws.on("message", (data, isBinary) => {
const buffer = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data as Buffer);
const text = isBinary ? null : buffer.toString("utf8");
wireInbound.push({ isBinary, text });
transport.onmessage?.({
data: isBinary
? buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
: buffer.toString("utf8"),
data: text ?? buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
isBinary,
});
});
@@ -202,6 +215,12 @@ async function openUpdatedRelayClient(args: {
channel,
serverInfo: serverInfoMessage.message.payload,
messages,
wireOutbound,
wireInbound,
retryHello: () => {
if (helloText === undefined) throw new Error("Missing relay handshake hello");
transport.send(helloText);
},
waitFor,
close: () => ws.close(),
};
@@ -987,11 +1006,31 @@ async function waitForCapturedLog(
expect(client.channel.securityMode()).toBe("protected");
expect(client.serverInfo.features?.relayProtectedSecurity).toBe(true);
await client.channel.send(JSON.stringify({ type: "ping" }));
const pingPayload = JSON.stringify({ type: "ping" });
const inboundBeforeRetry = client.wireInbound.length;
client.retryHello();
const outboundBeforePing = client.wireOutbound.length;
await client.channel.send(pingPayload);
const pong = await client.waitFor(
(message) => (message as { type?: string }).type === "pong",
);
expect(pong).toEqual({ type: "pong" });
// Handshake frames (e2ee_hello / e2ee_ready) are text; every protected
// application JSON frame (hello, server_info, ping, pong) crosses as binary.
expect(client.wireOutbound[0]?.isBinary).toBe(false);
const readyText = client.wireInbound[0]?.text;
if (readyText == null) throw new Error("Missing text relay handshake ready");
expect(JSON.parse(readyText)).toMatchObject({ type: "e2ee_ready" });
expect(client.wireInbound.slice(inboundBeforeRetry)).toContainEqual({
isBinary: false,
text: readyText,
});
const pingWire = client.wireOutbound[outboundBeforePing];
expect(pingWire?.isBinary).toBe(true);
expect(pingWire?.byteLength).toBe(client.channel.outboundWireByteLength(pingPayload));
const applicationFrames = client.wireInbound.filter((frame) => frame.text !== readyText);
expect(applicationFrames.length).toBeGreaterThanOrEqual(2);
expect(applicationFrames.every((frame) => frame.isBinary)).toBe(true);
await waitForCapturedLog(
lines,
(line) => line.includes('"securityMode":"protected"'),