Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 22c84c59f6 polish(app): smart-fill Direct connection form on paste (#12099)
* feat(app): smart-fill Direct connection form when pasting host:port or URI

Pasting a host:port, bracketed IPv6 address, or direct connection URI into the Direct connection form now splits and populates Host, Port, Use SSL, and Password instead of leaving the raw string in Host or kicking tcp:// URIs out of Form mode.

Unifies address parsing in direct-connection-host.ts so form normalization, URI-to-Form conversion, and smart paste share one parser. Handles web paste events directly when replacing the field (avoiding mid-string paste interference) and detects multi-character paste in onChangeText for native platforms without fighting manual typing or bare IPv6 entry.

* fix(app): preserve typed URI settings, clear password on tcp paste, and track native selection

Addresses review feedback on Direct connection smart-paste:
- Clears any previous host password when pasting a tcp:// URI without ?password=, while still preserving user-entered password on plain host:port or http(s)/ws(s) pastes.
- Resolves explicit scheme, port, ssl, and password from a manually typed URI in Host on Connect and Form-to-URI mode switching instead of dropping query settings.
- Requires decimal digits for ports in buildDirectConnectionUri so non-decimal IPv6 ports like [::1]:0x10 are rejected instead of parsed as hex.
- Tracks onSelectionChange on Host and Port so native platforms accurately distinguish full-field replacements from partial pastes.

* fix(app): commit typed Host URI into form fields on blur, edit, and connect

Eliminates conflicting sources of truth when a user manually types a URI into Host: leaving Host, editing Port/SSL/Password, switching modes, or clicking Connect now commits the parsed URI into the visible form fields so password retries and subsequent edits always control the next connection attempt.

* fix(app): sync Direct connection inputs when SSL toggle or Password commits Host

Routes handleToggleUseTls and handlePasswordChange through syncFormInputs so committing a manually typed URI in Host while Host still has focus (such as tapping Use SSL on native) updates the displayed Host, Port, and Password inputs immediately.

* fix(app): defer Host blur commit when clicking Use SSL checkbox

When clicking Use SSL while Host still holds a typed URI on web, Host blurs before the checkbox press fires. Deferring the blur commit when relatedTarget is the Use SSL toggle lets handleToggleUseTls own the single commit and toggle so clicking an unchecked Use SSL after typing an https:// URL leaves SSL enabled.
2026-12-05 13:13:54 +07:00
7 changed files with 1284 additions and 106 deletions
@@ -41,6 +41,9 @@ import {
connectDirectHost,
connectDirectHostExpectingPassword,
pasteIntoDirectHost,
pasteClipboardIntoDirectField,
pasteIntoMiddleOfDirectHost,
typeDirectHostCharacters,
fillDirectHostPromptPassword,
openCompactSettings,
expectCompactSettingsList,
@@ -56,6 +59,7 @@ import {
fillDirectHostUri,
expectDirectHostFormValues,
expectDirectHostSslEnabled,
expectDirectHostSslDisabled,
fillDirectHostAddress,
toggleDirectHostSsl,
expectDirectHostUriValue,
@@ -373,6 +377,110 @@ 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,6 +455,46 @@ 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,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
parseDirectConnectionPaste,
} from "./direct-connection-host";
const labels = {
hostRequired: "host required",
@@ -57,6 +61,26 @@ 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");
});
@@ -64,5 +88,102 @@ 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,52 +19,297 @@ export interface NormalizedDirectConnectionHost {
isIpv6: boolean;
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
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,
};
}
/**
* 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 {
let host = input.trim().replace(SCHEME_PATTERN, "");
const suffixIndex = host.search(/[/?#]/);
if (suffixIndex !== -1) {
host = host.slice(0, suffixIndex);
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 };
}
}
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 };
return {
host: address.host,
port: address.port || null,
isIpv6: address.isIpv6,
};
}
export function buildDirectConnectionUri(
draft: DirectConnectionHostInput,
labels: DirectConnectionHostLabels,
): string {
const normalized = normalizeDirectConnectionHost(draft.host);
const port = Number((normalized.port ?? draft.port).trim());
if (!normalized.host) {
const resolved = resolveDirectHostDraft(draft);
if (!resolved.host) {
throw new Error(labels.hostRequired);
}
if (!Number.isInteger(port) || port < 1 || port > 65535) {
const port = parseValidPortNumber(resolved.port);
if (port === null) {
throw new Error(labels.invalidPort);
}
return serializeConnectionUriForStorage({
host: normalized.host,
host: resolved.host,
port,
isIpv6: normalized.isIpv6,
useTls: draft.useTls,
...(draft.password ? { password: draft.password } : {}),
isIpv6: resolved.isIpv6,
useTls: resolved.useTls,
...(resolved.password ? { password: resolved.password } : {}),
});
}
@@ -1,8 +1,16 @@
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useCallback, useMemo, useRef, useState } from "react";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
import {
Alert,
Text,
View,
type LayoutChangeEvent,
type NativeSyntheticEvent,
type TextInputSelectionChangeEventData,
} 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";
@@ -27,11 +35,14 @@ 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,
@@ -41,6 +52,7 @@ import {
type DirectConnectionMode,
type DirectConnectionUri,
type ResolvedDirectConnection,
type TextSelection,
} from "./direct-connection";
const FLEX_ONE_STYLE = { flex: 1 } as const;
@@ -468,6 +480,22 @@ 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,
@@ -481,6 +509,13 @@ 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], []);
@@ -493,22 +528,188 @@ 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) => onChange(editHost(input, host)),
[input, onChange],
(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],
);
const handlePortChange = useCallback(
(port: string) => onChange(editForm(input, { port })),
[input, onChange],
(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],
);
const handlePasswordChange = useCallback(
(password: string) => onChange(editForm(input, { password })),
[input, onChange],
(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],
);
const handleToggleUseTls = useCallback(() => {
if (isSaving) return;
onChange(editForm(input, { useTls: !input.useTls }));
}, [input, isSaving, onChange]);
const next = editForm(input, { useTls: !input.useTls });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
}, [input, isSaving, onChange, syncFormInputs]);
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
const handleTogglePasswordVisibility = useCallback(() => {
setIsPasswordVisible((current) => !current);
@@ -522,13 +723,15 @@ 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={fieldEvents.onBlur}
onBlur={handleHostBlur}
autoFocus={fieldEvents.autoFocus}
placeholder="localhost"
style={styles.input}
@@ -542,11 +745,13 @@ 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"
@@ -562,6 +767,7 @@ function DirectFormFields({
</View>
<PressHighlight
ref={sslToggleRef}
style={styles.checkboxRow}
onPress={handleToggleUseTls}
disabled={isSaving}
@@ -586,6 +792,7 @@ 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,11 +1,14 @@
import { describe, expect, it } from "vitest";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -28,7 +31,17 @@ const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
const { host = "", ...rest } = fields;
return editForm(editHost(openDirectConnection(), host), rest);
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;
}
function uri(text: string): DirectConnectionInput {
@@ -129,6 +142,20 @@ 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", () => {
@@ -153,18 +180,348 @@ describe("switching from URI to Form", () => {
});
describe("typing in Host", () => {
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("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("moves a typed or pasted URI to URI mode", () => {
expect(editHost(openDirectConnection(), "tcp://h:7000?password=x")).toEqual({
mode: "uri",
uri: "tcp://h:7000?password=x",
prompt: null,
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({
mode: "uri",
uri: "tcp://secure.example.test:7443?ssl=true&password=example",
});
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,
@@ -177,6 +534,11 @@ describe("typing in Host", () => {
uri: OFFER_LINK,
prompt: null,
});
expect(pasteDirectConnection(openDirectConnection(), OFFER_LINK)).toEqual({
mode: "uri",
uri: OFFER_LINK,
prompt: null,
});
});
});
@@ -1,6 +1,11 @@
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
defaultPortForDirectScheme,
isPairingLink,
parseDirectConnectionAddress,
parseDirectConnectionPaste,
resolveDirectHostDraft,
resolveDirectSchemeTls,
type DirectConnectionHostLabels,
} from "@/components/direct-connection-host";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
@@ -38,7 +43,6 @@ 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: "" };
@@ -59,21 +63,97 @@ 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 { ...input, ...fields };
return { ...commitDirectFormHost(input), ...fields };
}
/** 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 {
/**
* 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 {
if (input.mode !== "form") return input;
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.host, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
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;
@@ -100,11 +180,12 @@ export function resolveConnection(
input: DirectConnectionInput,
labels: DirectConnectionHostLabels,
): ResolvedDirectConnection {
if (input.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(input, labels));
const effective = commitHost(input);
if (effective.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(effective, labels));
}
const uri = input.uri.trim();
const promptPassword = input.prompt?.password || undefined;
const uri = effective.uri.trim();
const promptPassword = effective.prompt?.password || undefined;
if (isPairingLink(uri)) {
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
}
@@ -123,43 +204,85 @@ function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectCo
};
}
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
function isPairingLink(uri: string): boolean {
const trimmed = uri.trim();
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);
return (
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
next.length >= prefix.length + suffix.length && next.startsWith(prefix) && next.endsWith(suffix)
);
}
function looksLikeUri(text: string): boolean {
return TCP_URI_PATTERN.test(text.trim()) || isPairingLink(text);
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);
}
// 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 normalized = normalizeDirectConnectionHost(input.host);
if (!normalized.host) return "";
const host = normalized.isIpv6 ? `[${normalized.host}]` : normalized.host;
const port = normalized.port ?? input.port.trim();
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 query = new URLSearchParams();
if (input.useTls) query.set("ssl", "true");
if (input.password) query.set("password", input.password);
if (resolved.useTls) query.set("ssl", "true");
if (resolved.password) query.set("password", resolved.password);
const search = query.toString();
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
return `tcp://${host}:${resolved.port}${search ? `?${search}` : ""}`;
}
function uriToForm(uri: string): DirectConnectionForm {
const address = splitUri(uri);
const address = parseDirectConnectionAddress(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: address.port ?? DEFAULT_PORT,
useTls: address.query.get("ssl") === "true",
password: address.query.get("password") ?? "",
port,
useTls: resolveDirectSchemeTls(address.scheme, address.sslParam) ?? false,
password: address.password ?? "",
};
}
@@ -174,35 +297,7 @@ export function uriHostLabel(uri: string): string | null {
return null;
}
}
const address = splitUri(trimmed);
const address = parseDirectConnectionAddress(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 };
}