mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
Switch Direct connection between Form and URI modes (#11402)
* feat(app): switch Direct connection between Form and URI modes
The Advanced disclosure kept a second copy of the address. Connect read
the Host and Port fields while a tcp:// URI sat in the open Advanced
field, so a blank Host failed with "Host is required" and an edited URI
connected to the old address.
The step now holds one input whose type is the mode. Connect reads only
that input, so a hidden copy cannot exist. Switching modes converts the
input and never fails; an invalid port carries over as text so Connect
reports it. A tcp:// or relay:// address typed into Host moves to URI
mode, where its password and SSL settings count. A pairing link keeps
the Form segment disabled because it cannot be expressed as fields.
URI mode has no Password field, so a rejected password opens an inline
"Password for {host}" prompt, the same as Paste pairing link. URI mode
keeps the Form body's height and the actions sit in the sheet footer,
so Cancel and Connect stay put when the mode changes.
Closes #5495
Co-authored-by: thecardcheat <pitt.joshua.miller@gmail.com>
* fix(app): treat #offer= pairing links in Direct connection as a URI
paseo daemon pair prints an #offer= link next to the relay:// URI.
Pasted into Host it stayed in Form mode and probed the app's web host
as a daemon. All three pairing link formats now share one check.
* fix(app): show the whole Direct connection form on short phones
The compact sheet opened at the shared 65% stop. With Password always
visible and the mode switch above it, the form needs about 485dp of
sheet, so on phones about 690dp tall or shorter the footer covered the
Password field and its eye button. The sheet now opens at 80%.
---------
Co-authored-by: thecardcheat <pitt.joshua.miller@gmail.com>
This commit is contained in:
co-authored by
thecardcheat
parent
e31f379d54
commit
96fee23fbd
@@ -35,7 +35,13 @@ import {
|
||||
expectSettingsHeader,
|
||||
openAddHostFlow,
|
||||
selectHostConnectionType,
|
||||
toggleHostAdvanced,
|
||||
selectDirectConnectionMode,
|
||||
expectDirectConnectionMode,
|
||||
expectDirectFormModeDisabled,
|
||||
connectDirectHost,
|
||||
connectDirectHostExpectingPassword,
|
||||
pasteIntoDirectHost,
|
||||
fillDirectHostPromptPassword,
|
||||
openCompactSettings,
|
||||
expectCompactSettingsList,
|
||||
expectSettingsSidebarVisible,
|
||||
@@ -50,11 +56,11 @@ import {
|
||||
fillDirectHostUri,
|
||||
expectDirectHostFormValues,
|
||||
expectDirectHostSslEnabled,
|
||||
expectDirectHostSslDisabled,
|
||||
fillDirectHostAddress,
|
||||
toggleDirectHostSsl,
|
||||
expectDirectHostUriValue,
|
||||
expectDirectHostUriHidden,
|
||||
expectDirectFormFullyVisible,
|
||||
expectDiagnosticsContent,
|
||||
expectAboutContent,
|
||||
expectGeneralContent,
|
||||
@@ -71,6 +77,7 @@ import {
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
@@ -327,44 +334,105 @@ test.describe("Settings sidebar navigation", () => {
|
||||
await verifyLegacyHostSettingsRedirect(page);
|
||||
});
|
||||
|
||||
test("direct connection advanced URI round-trips SSL and password into the form", async ({
|
||||
page,
|
||||
}) => {
|
||||
test("direct connection converts between Form and URI modes", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await expectAddHostMethodOptions(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectConnectionMode(page, "Form");
|
||||
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
await toggleHostAdvanced(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslDisabled(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret");
|
||||
await toggleHostAdvanced(page);
|
||||
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
await test.step("Form fields become a URI", async () => {
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await toggleDirectHostSsl(page);
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
await test.step("a URI becomes Form fields", async () => {
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await selectDirectConnectionMode(page, "Form");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
});
|
||||
|
||||
await test.step("a pairing link pasted into Host stays a URI", async () => {
|
||||
const link = "relay://relay.paseo.test:443/srv_e2e_pairing?key=daemon-key&ssl=true";
|
||||
await pasteIntoDirectHost(page, link);
|
||||
await expectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, link);
|
||||
await expectDirectFormModeDisabled(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("direct connection connects to a URI with Host blank", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection connects to an edited URI instead of the form", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await fillDirectHostAddress(page, "127.0.0.1", "9");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://127.0.0.1:9");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection sends the password in a URI and asks again when it is wrong", async ({
|
||||
page,
|
||||
}) => {
|
||||
const password = "e2e uri password";
|
||||
const daemon = await startIsolatedHostDaemon("srv_e2e_uri_password_host", {
|
||||
environment: { ...process.env, PASEO_PASSWORD: password },
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
|
||||
await test.step("a URI with the password connects with one tap", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
`tcp://127.0.0.1:${daemon.port}?password=${encodeURIComponent(password)}`,
|
||||
);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
await test.step("a wrong password asks for the host's password inline", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${daemon.port}?password=wrong`);
|
||||
await connectDirectHostExpectingPassword(page, `127.0.0.1:${daemon.port}`);
|
||||
await fillDirectHostPromptPassword(page, password);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Escape lets settings dropdowns and modals close before leaving settings", async ({
|
||||
@@ -697,3 +765,16 @@ test("docked navigation keeps its density and Settings preserves reading width",
|
||||
await expectSettingsSidebarHidden(page);
|
||||
await expectAppearanceContent(page);
|
||||
});
|
||||
|
||||
test.describe("Settings — small phone", () => {
|
||||
test.use({ viewport: { width: 360, height: 640 } });
|
||||
|
||||
test("direct connection shows the whole form above Cancel and Connect", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openCompactSidebar(page);
|
||||
await openSettingsFromCompactSidebar(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectFormFullyVisible(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -111,7 +111,7 @@ Keep generated screenshots, recordings, and run logs outside the repository.
|
||||
confirmation. It first types without tapping the input to verify autofocus, then cancels the
|
||||
confirmation, closes and reopens the underlying sheet, confirms again,
|
||||
and completes the password retry. `stacked-settings.ad` checks the same return and retry through
|
||||
Settings → add host → Direct connection → Advanced. Run both on phones and tablets so both the
|
||||
Settings → add host → Direct connection → URI. Run both on phones and tablets so both the
|
||||
bottom sheet and centered dialog are exercised.
|
||||
|
||||
These integration journeys require the host-confirmation flow in the test app. Include both the
|
||||
@@ -146,7 +146,7 @@ Android uses the same journeys: copy each script outside the repository, change
|
||||
artifacts, and sessions separate from other runs. These host-dependent journeys remain outside the
|
||||
default mobile suite, alongside the existing modal-sheet scripts.
|
||||
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the advanced URI field triggers a
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the Connection URI field triggers a
|
||||
repeated-update error with both the parent and stacked-sheet implementations. Entering the complete
|
||||
URI one character at a time passed with both implementations; faster typing remains unverified.
|
||||
On iPad, replacing the field a second time appends text. For this Settings journey, use the
|
||||
|
||||
@@ -10,7 +10,7 @@ wait "id=\"add-host-method-direct\"" 10000
|
||||
screenshot "${OUT}/10-add-host-methods.png"
|
||||
press "id=\"add-host-method-direct\""
|
||||
wait stable
|
||||
press "id=\"direct-host-advanced-toggle\""
|
||||
press "id=\"direct-mode-uri\""
|
||||
wait stable
|
||||
fill "id=\"direct-host-uri-input\"" "${PAIRING_LINK}"
|
||||
wait stable
|
||||
@@ -32,9 +32,9 @@ wait "id=\"host-confirmation-connect\"" 10000
|
||||
screenshot "${OUT}/14-add-host-confirmation-reopens.png"
|
||||
press "id=\"host-confirmation-connect\""
|
||||
wait stable
|
||||
wait "id=\"direct-password-input\"" 20000
|
||||
wait "id=\"direct-uri-password-input\"" 20000
|
||||
screenshot "${OUT}/15-add-host-password.png"
|
||||
fill "id=\"direct-password-input\"" "${PASSWORD}"
|
||||
fill "id=\"direct-uri-password-input\"" "${PASSWORD}"
|
||||
wait stable
|
||||
press "id=\"direct-host-submit\""
|
||||
wait stable
|
||||
|
||||
@@ -258,8 +258,37 @@ export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string)
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
function directConnectionModeSegment(page: Page, mode: "Form" | "URI") {
|
||||
return page.getByTestId("direct-mode").getByRole("button", { name: mode, exact: true });
|
||||
}
|
||||
|
||||
export async function selectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await directConnectionModeSegment(page, mode).click();
|
||||
await expectDirectConnectionMode(page, mode);
|
||||
}
|
||||
|
||||
export async function expectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, mode)).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
export async function expectDirectFormModeDisabled(page: Page): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, "Form")).toBeDisabled();
|
||||
}
|
||||
|
||||
export async function connectDirectHost(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function connectDirectHostExpectingPassword(page: Page, host: string): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByText(`Password for ${host}`, { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function fillDirectHostPromptPassword(page: Page, password: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host password", exact: true }).fill(password);
|
||||
}
|
||||
|
||||
export async function openCompactSettings(page: Page, expectedStartRoute: string): Promise<void> {
|
||||
@@ -422,6 +451,10 @@ export async function fillDirectHostAddress(page: Page, host: string, port: stri
|
||||
await page.getByRole("textbox", { name: "Port", exact: true }).fill(port);
|
||||
}
|
||||
|
||||
export async function pasteIntoDirectHost(page: Page, text: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
|
||||
}
|
||||
|
||||
export async function toggleDirectHostSsl(page: Page): Promise<void> {
|
||||
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
|
||||
}
|
||||
@@ -439,6 +472,12 @@ export async function expectDirectHostUriHidden(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-host-uri-input")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** The whole form shows above Cancel and Connect, with nothing cut off by the footer. */
|
||||
export async function expectDirectFormFullyVisible(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-password-input")).toBeInViewport({ ratio: 1 });
|
||||
await expect(page.getByTestId("direct-password-visibility-toggle")).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectDiagnosticsContent(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Run" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Play test" })).toBeVisible();
|
||||
|
||||
@@ -11,11 +11,6 @@ describe("pairing target password", () => {
|
||||
expect(target.changeUrl(second)).toBe(false);
|
||||
});
|
||||
|
||||
it("clears the direct form credential when its advanced URI changes to a relay target", () => {
|
||||
const target = new PairingTargetTracker("", true);
|
||||
expect(target.changeUrl("relay://relay.example:443/srv_new?key=BBBB&ssl=true")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the password when a relay URI receives harmless whitespace", () => {
|
||||
const uri = "relay://relay.example:443/srv_a?key=AAAA&ssl=true";
|
||||
const target = new PairingTargetTracker(uri);
|
||||
|
||||
@@ -19,8 +19,8 @@ function pairingTarget(url: string): string | null {
|
||||
export class PairingTargetTracker {
|
||||
private currentTarget: string | null;
|
||||
|
||||
constructor(initialUrl = "", startsFromDirectForm = false) {
|
||||
this.currentTarget = pairingTarget(initialUrl) ?? (startsFromDirectForm ? "direct-form" : null);
|
||||
constructor(initialUrl = "") {
|
||||
this.currentTarget = pairingTarget(initialUrl);
|
||||
}
|
||||
|
||||
changeUrl(nextUrl: string): boolean {
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useCallback, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert, Text, View } 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, ChevronDown, ChevronRight, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import { Check, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
|
||||
import { parseConnectionUri, serializeConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { buildConnectionFailureCopy } from "@/components/connection-failure-copy";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
@@ -15,24 +14,30 @@ import {
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PairingTargetTracker } from "@/components/pair-link-credentials";
|
||||
import { buildDirectConnectionUri } from "@/components/direct-connection-host";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard/availability";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
editHost,
|
||||
editPromptPassword,
|
||||
editUri,
|
||||
openDirectConnection,
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
type DirectConnectionMode,
|
||||
type DirectConnectionUri,
|
||||
type ResolvedDirectConnection,
|
||||
} from "./direct-connection";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
|
||||
interface DirectConnectionDraft {
|
||||
host: string;
|
||||
port: string;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface PreparedDirectConnection {
|
||||
uri: string;
|
||||
endpoint: string;
|
||||
useTls: boolean;
|
||||
password?: string;
|
||||
}
|
||||
// The sheet's default first stop (65%) cuts off Password on phones about 690dp tall or shorter.
|
||||
// 80% fits the whole form above Cancel and Connect down to 640dp.
|
||||
const SNAP_POINTS = ["80%", "92%"];
|
||||
|
||||
interface DirectConnectionLabels {
|
||||
hostRequired: string;
|
||||
@@ -49,6 +54,9 @@ interface DirectConnectionLabels {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
modeBody: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
field: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
@@ -114,26 +122,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.accent,
|
||||
borderColor: theme.colors.accent,
|
||||
},
|
||||
advancedToggle: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
alignSelf: "flex-start",
|
||||
paddingVertical: theme.spacing[1],
|
||||
},
|
||||
advancedText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
actions: {
|
||||
footer: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
helper: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
error: {
|
||||
color: theme.colors.destructive,
|
||||
@@ -141,33 +133,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
function prepareDirectConnection(
|
||||
draft: DirectConnectionDraft,
|
||||
labels: DirectConnectionLabels,
|
||||
): PreparedDirectConnection {
|
||||
const parsed = parseConnectionUri(buildDirectConnectionUri(draft, labels));
|
||||
const endpoint = parsed.isIpv6
|
||||
? `[${parsed.host}]:${parsed.port}`
|
||||
: `${parsed.host}:${parsed.port}`;
|
||||
|
||||
return {
|
||||
uri: serializeConnectionUri(parsed),
|
||||
endpoint,
|
||||
useTls: parsed.useTls,
|
||||
...(parsed.password ? { password: parsed.password } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function draftFromConnectionUri(uri: string): DirectConnectionDraft {
|
||||
const parsed = parseConnectionUri(uri);
|
||||
return {
|
||||
host: parsed.host,
|
||||
port: String(parsed.port),
|
||||
useTls: parsed.useTls,
|
||||
password: parsed.password ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export interface AddHostModalProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
@@ -198,31 +163,19 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
const { probeAndUpsertDirectConnection, beginLinkPairing } = useHostMutations();
|
||||
const [linkPairing] = useState(() => beginLinkPairing());
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const keyboardPresent = useHardwareKeyboardPresent();
|
||||
|
||||
const [input, setInput] = useState<DirectConnectionInput>(openDirectConnection);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [host, setHost] = useState("");
|
||||
const [port, setPort] = useState("6767");
|
||||
const [useTls, setUseTls] = useState(false);
|
||||
const [password, setPassword] = useState("");
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
|
||||
const [advancedUri, setAdvancedUri] = useState("");
|
||||
const [inputResetKey, bumpInputResetKey] = useReducer((key: number) => key + 1, 0);
|
||||
const advancedTarget = useRef(new PairingTargetTracker("", true));
|
||||
// Switching modes mounts the other mode's fields. They take focus when the user was typing
|
||||
// or has a keyboard, so a phone's keyboard stays up instead of closing on the switch.
|
||||
const [focusModeBody, setFocusModeBody] = useState(false);
|
||||
const fieldFocused = useRef(false);
|
||||
// URI mode keeps the Form body's height, so Cancel and Connect stay where they are.
|
||||
const [formBodyHeight, setFormBodyHeight] = useState<number | null>(null);
|
||||
|
||||
const connectIcon = useMemo(() => <ThemedLink2 size={16} />, []);
|
||||
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
|
||||
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
|
||||
const checkboxStyle = useMemo(
|
||||
() => [styles.checkbox, useTls ? styles.checkboxChecked : null],
|
||||
[useTls],
|
||||
);
|
||||
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
|
||||
const useTlsAccessibilityState = useMemo(
|
||||
() => ({ checked: useTls, disabled: isSaving }),
|
||||
[isSaving, useTls],
|
||||
);
|
||||
const directConnectionLabels = useMemo<DirectConnectionLabels>(
|
||||
() => ({
|
||||
hostRequired: t("pairing.direct.errors.hostRequired"),
|
||||
@@ -241,6 +194,21 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("pairing.direct.title") }), [t]);
|
||||
|
||||
const formAvailable = canSwitchToForm(input);
|
||||
const modeOptions = useMemo<SegmentedControlOption<DirectConnectionMode>[]>(
|
||||
() => [
|
||||
{
|
||||
value: "form",
|
||||
label: t("pairing.direct.modes.form"),
|
||||
testID: "direct-mode-form",
|
||||
disabled: !formAvailable,
|
||||
...(formAvailable ? {} : { tooltip: t("pairing.direct.modes.uriOnlyLink") }),
|
||||
},
|
||||
{ value: "uri", label: t("pairing.direct.modes.uri"), testID: "direct-mode-uri" },
|
||||
],
|
||||
[formAvailable, t],
|
||||
);
|
||||
|
||||
// Each open mounts a fresh form (see AddHostModal), so closing needs no reset.
|
||||
const handleClose = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
@@ -252,71 +220,37 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
(onCancel ?? onClose)();
|
||||
}, [isSaving, onCancel, onClose]);
|
||||
|
||||
const handleSaveRelay = useCallback(
|
||||
async (relayUri: string) => {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
const commitInput = useCallback(
|
||||
(next: DirectConnectionInput) => {
|
||||
if (next.mode !== input.mode) {
|
||||
setFocusModeBody(keyboardPresent || fieldFocused.current);
|
||||
setErrorMessage("");
|
||||
const result = await linkPairing.submit(relayUri, password || undefined);
|
||||
if (result.status === "cancelled") return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection,
|
||||
);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
setInput(next);
|
||||
},
|
||||
[
|
||||
daemons,
|
||||
directConnectionLabels.invalidConnection,
|
||||
handleClose,
|
||||
linkPairing,
|
||||
onSaved,
|
||||
password,
|
||||
],
|
||||
[input.mode, keyboardPresent],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (isSaving) return;
|
||||
|
||||
const relayUri = isAdvancedOpen ? advancedUri.trim() : "";
|
||||
if (relayUri.startsWith("relay://") || relayUri.includes("#connect=")) {
|
||||
await handleSaveRelay(relayUri);
|
||||
return;
|
||||
}
|
||||
|
||||
let connection: PreparedDirectConnection;
|
||||
try {
|
||||
connection = prepareDirectConnection(
|
||||
{ host, port, useTls, password },
|
||||
directConnectionLabels,
|
||||
);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
|
||||
setErrorMessage(message);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
|
||||
const { profile, serverId, hostname } = await probeAndUpsertDirectConnection({
|
||||
const connect = useCallback(
|
||||
async (connection: ResolvedDirectConnection) => {
|
||||
if (connection.kind === "relay") {
|
||||
const result = await linkPairing.submit(connection.link, connection.password);
|
||||
return result.status === "cancelled" ? null : result;
|
||||
}
|
||||
return probeAndUpsertDirectConnection({
|
||||
endpoint: connection.endpoint,
|
||||
useTls: connection.useTls,
|
||||
...(connection.password ? { password: connection.password } : {}),
|
||||
});
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
},
|
||||
[linkPairing, probeAndUpsertDirectConnection],
|
||||
);
|
||||
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const describeFailure = useCallback(
|
||||
(connection: ResolvedDirectConnection, error: unknown) => {
|
||||
if (connection.kind === "relay") {
|
||||
return error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
|
||||
}
|
||||
const {
|
||||
title,
|
||||
detail,
|
||||
@@ -326,108 +260,224 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
error,
|
||||
labels: directConnectionLabels,
|
||||
});
|
||||
let combined: string;
|
||||
if (rawDetail && detail && rawDetail !== detail) {
|
||||
combined = `${title}\n${detail}\n${t("pairing.direct.errors.details", {
|
||||
detail: rawDetail,
|
||||
})}`;
|
||||
} else if (detail) {
|
||||
combined = `${title}\n${detail}`;
|
||||
} else {
|
||||
combined = title;
|
||||
return `${title}\n${detail}\n${t("pairing.direct.errors.details", { detail: rawDetail })}`;
|
||||
}
|
||||
setErrorMessage(combined);
|
||||
if (!isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), combined);
|
||||
return detail ? `${title}\n${detail}` : title;
|
||||
},
|
||||
[directConnectionLabels, t],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (isSaving) return;
|
||||
|
||||
let connection: ResolvedDirectConnection;
|
||||
try {
|
||||
connection = resolveConnection(input, directConnectionLabels);
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
const result = await connect(connection);
|
||||
if (!result) return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const message = describeFailure(connection, error);
|
||||
setErrorMessage(message);
|
||||
// URI mode has no Password field, so a rejected password is asked for here.
|
||||
if (input.mode === "uri" && getConnectionAuthFailureReason(error)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
return;
|
||||
}
|
||||
if (connection.kind === "direct" && !isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), message);
|
||||
}
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}, [
|
||||
advancedUri,
|
||||
connect,
|
||||
daemons,
|
||||
describeFailure,
|
||||
directConnectionLabels,
|
||||
handleClose,
|
||||
host,
|
||||
isAdvancedOpen,
|
||||
input,
|
||||
isMobile,
|
||||
isSaving,
|
||||
onSaved,
|
||||
password,
|
||||
port,
|
||||
probeAndUpsertDirectConnection,
|
||||
t,
|
||||
handleSaveRelay,
|
||||
useTls,
|
||||
]);
|
||||
|
||||
const handleSubmitEditing = useCallback(() => {
|
||||
const handleSubmit = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
|
||||
const handleSavePress = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
const handleModeChange = useCallback(
|
||||
(mode: DirectConnectionMode) => commitInput(switchMode(input, mode)),
|
||||
[commitInput, input],
|
||||
);
|
||||
|
||||
const handleChangeAdvancedUri = useCallback((next: string) => {
|
||||
if (advancedTarget.current.changeUrl(next)) {
|
||||
setPassword("");
|
||||
bumpInputResetKey();
|
||||
setErrorMessage("");
|
||||
}
|
||||
setAdvancedUri(next);
|
||||
const handleFieldFocus = useCallback(() => {
|
||||
fieldFocused.current = true;
|
||||
}, []);
|
||||
|
||||
const handleToggleUseTls = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
setUseTls((current) => !current);
|
||||
}, [isSaving]);
|
||||
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
const handleFieldBlur = useCallback(() => {
|
||||
fieldFocused.current = false;
|
||||
}, []);
|
||||
|
||||
const handleToggleAdvanced = useCallback(() => {
|
||||
if (!isAdvancedOpen) {
|
||||
advancedTarget.current = new PairingTargetTracker("", true);
|
||||
try {
|
||||
setAdvancedUri(
|
||||
buildDirectConnectionUri({ host, port, useTls, password }, directConnectionLabels),
|
||||
);
|
||||
} catch {
|
||||
setAdvancedUri("");
|
||||
}
|
||||
setErrorMessage("");
|
||||
setIsAdvancedOpen(true);
|
||||
return;
|
||||
}
|
||||
const handleFormBodyLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setFormBodyHeight(event.nativeEvent.layout.height);
|
||||
}, []);
|
||||
|
||||
try {
|
||||
const next = draftFromConnectionUri(advancedUri);
|
||||
setHost(next.host);
|
||||
setPort(next.port);
|
||||
setUseTls(next.useTls);
|
||||
setPassword(next.password);
|
||||
setErrorMessage("");
|
||||
bumpInputResetKey();
|
||||
} catch {
|
||||
setErrorMessage("");
|
||||
}
|
||||
setIsAdvancedOpen(false);
|
||||
}, [advancedUri, directConnectionLabels, host, isAdvancedOpen, password, port, useTls]);
|
||||
const uriBodyStyle = useMemo(
|
||||
() => [styles.modeBody, formBodyHeight === null ? null : { minHeight: formBodyHeight }],
|
||||
[formBodyHeight],
|
||||
);
|
||||
|
||||
const AdvancedIcon = isAdvancedOpen ? ThemedChevronDown : ThemedChevronRight;
|
||||
const PasswordIcon = isPasswordVisible ? ThemedEyeOff : ThemedEye;
|
||||
const fieldEvents = useMemo<FieldEvents>(
|
||||
() => ({
|
||||
autoFocus: focusModeBody,
|
||||
onFocus: handleFieldFocus,
|
||||
onBlur: handleFieldBlur,
|
||||
onSubmit: handleSubmit,
|
||||
}),
|
||||
[focusModeBody, handleFieldBlur, handleFieldFocus, handleSubmit],
|
||||
);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
onPress={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("pairing.direct.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
onPress={handleSubmit}
|
||||
disabled={isSaving}
|
||||
leftIcon={connectIcon}
|
||||
testID="direct-host-submit"
|
||||
>
|
||||
{isSaving ? t("pairing.direct.actions.connecting") : t("pairing.direct.actions.connect")}
|
||||
</Button>
|
||||
</View>
|
||||
),
|
||||
[connectIcon, handleCancel, handleSubmit, isSaving, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={handleClose}
|
||||
footer={footer}
|
||||
snapPoints={SNAP_POINTS}
|
||||
testID="add-host-modal"
|
||||
>
|
||||
<Text style={styles.helper}>{t("pairing.direct.helper")}</Text>
|
||||
<SegmentedControl
|
||||
options={modeOptions}
|
||||
value={input.mode}
|
||||
onValueChange={handleModeChange}
|
||||
fill
|
||||
testID="direct-mode"
|
||||
/>
|
||||
|
||||
{input.mode === "form" ? (
|
||||
<View key="form" style={styles.modeBody} onLayout={handleFormBodyLayout}>
|
||||
<DirectFormFields
|
||||
input={input}
|
||||
isSaving={isSaving}
|
||||
fieldEvents={fieldEvents}
|
||||
onChange={commitInput}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View key="uri" style={uriBodyStyle}>
|
||||
<DirectUriFields
|
||||
input={input}
|
||||
isSaving={isSaving}
|
||||
fieldEvents={fieldEvents}
|
||||
onChange={commitInput}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface FieldEvents {
|
||||
/** Whether the mode's first field takes focus when it mounts. */
|
||||
autoFocus: boolean;
|
||||
onFocus: () => void;
|
||||
onBlur: () => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
function DirectFormFields({
|
||||
input,
|
||||
isSaving,
|
||||
fieldEvents,
|
||||
onChange,
|
||||
}: {
|
||||
input: DirectConnectionForm;
|
||||
isSaving: boolean;
|
||||
fieldEvents: FieldEvents;
|
||||
onChange: (next: DirectConnectionInput) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
|
||||
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
|
||||
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
|
||||
const checkboxStyle = useMemo(
|
||||
() => [styles.checkbox, input.useTls ? styles.checkboxChecked : null],
|
||||
[input.useTls],
|
||||
);
|
||||
const useTlsAccessibilityState = useMemo(
|
||||
() => ({ checked: input.useTls, disabled: isSaving }),
|
||||
[isSaving, input.useTls],
|
||||
);
|
||||
|
||||
const handleHostChange = useCallback(
|
||||
(host: string) => onChange(editHost(input, host)),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePortChange = useCallback(
|
||||
(port: string) => onChange(editForm(input, { port })),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePasswordChange = useCallback(
|
||||
(password: string) => onChange(editForm(input, { password })),
|
||||
[input, onChange],
|
||||
);
|
||||
const handleToggleUseTls = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
onChange(editForm(input, { useTls: !input.useTls }));
|
||||
}, [input, isSaving, onChange]);
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
}, []);
|
||||
|
||||
const PasswordIcon = isPasswordVisible ? ThemedEyeOff : ThemedEye;
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={styles.portRow}>
|
||||
<View style={hostFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
|
||||
@@ -435,9 +485,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-host-input"
|
||||
nativeID="direct-host-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.host")}
|
||||
initialValue={host}
|
||||
resetKey={`direct-host-${inputResetKey}`}
|
||||
onChangeText={setHost}
|
||||
initialValue={input.host}
|
||||
onChangeText={handleHostChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus={fieldEvents.autoFocus}
|
||||
placeholder="localhost"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
@@ -453,9 +505,10 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-port-input"
|
||||
nativeID="direct-port-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.port")}
|
||||
initialValue={port}
|
||||
resetKey={`direct-port-${inputResetKey}`}
|
||||
onChangeText={setPort}
|
||||
initialValue={input.port}
|
||||
onChangeText={handlePortChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
placeholder="6767"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
@@ -463,7 +516,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
keyboardType="number-pad"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleSubmitEditing}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
@@ -475,11 +528,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityLabel={t("pairing.direct.fields.useSsl")}
|
||||
accessibilityState={useTlsAccessibilityState}
|
||||
aria-checked={useTls}
|
||||
aria-checked={input.useTls}
|
||||
testID="direct-ssl-toggle"
|
||||
>
|
||||
<View style={checkboxStyle}>
|
||||
{useTls ? (
|
||||
{input.useTls ? (
|
||||
<View testID="direct-ssl-toggle-checked">
|
||||
<ThemedCheck size={14} />
|
||||
</View>
|
||||
@@ -495,9 +548,10 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-password-input"
|
||||
nativeID="direct-password-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.password")}
|
||||
initialValue={password}
|
||||
resetKey={`direct-password-${inputResetKey}`}
|
||||
onChangeText={setPassword}
|
||||
initialValue={input.password}
|
||||
onChangeText={handlePasswordChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
placeholder={t("pairing.direct.fields.optional")}
|
||||
style={passwordInputStyle}
|
||||
autoCapitalize="none"
|
||||
@@ -505,7 +559,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
secureTextEntry={!isPasswordVisible}
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleSubmitEditing}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
<PressHighlight
|
||||
style={styles.iconButton}
|
||||
@@ -523,63 +577,80 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DirectUriFields({
|
||||
input,
|
||||
isSaving,
|
||||
fieldEvents,
|
||||
onChange,
|
||||
}: {
|
||||
input: DirectConnectionUri;
|
||||
isSaving: boolean;
|
||||
fieldEvents: FieldEvents;
|
||||
onChange: (next: DirectConnectionInput) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handleUriChange = useCallback(
|
||||
(uri: string) => onChange(editUri(input, uri)),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePromptPasswordChange = useCallback(
|
||||
(password: string) => onChange(editPromptPassword(input, password)),
|
||||
[input, onChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={styles.field}>
|
||||
<PressHighlight
|
||||
style={styles.advancedToggle}
|
||||
onPress={handleToggleAdvanced}
|
||||
disabled={isSaving}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
isAdvancedOpen ? t("pairing.direct.advanced.hide") : t("pairing.direct.advanced.show")
|
||||
}
|
||||
testID="direct-host-advanced-toggle"
|
||||
>
|
||||
<AdvancedIcon size={16} />
|
||||
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
|
||||
</PressHighlight>
|
||||
{isAdvancedOpen ? (
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.connectionUri")}</Text>
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
initialValue={input.uri}
|
||||
onChangeText={handleUriChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus={fieldEvents.autoFocus}
|
||||
placeholder="tcp://localhost:6767?ssl=true"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{input.prompt ? (
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>
|
||||
{t("pairing.hostPassword.title", { host: input.prompt.host })}
|
||||
</Text>
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
initialValue={advancedUri}
|
||||
resetKey={`direct-host-uri-${inputResetKey}`}
|
||||
onChangeText={handleChangeAdvancedUri}
|
||||
placeholder="tcp://localhost:6767?ssl=true"
|
||||
style={styles.input}
|
||||
testID="direct-uri-password-input"
|
||||
accessibilityLabel={t("pairing.hostPassword.label")}
|
||||
placeholder={t("pairing.hostPassword.label")}
|
||||
initialValue={input.prompt.password}
|
||||
onChangeText={handlePromptPasswordChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus
|
||||
secureTextEntry
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleToggleAdvanced}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
style={styles.input}
|
||||
/>
|
||||
) : null}
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
onPress={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("pairing.direct.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
onPress={handleSavePress}
|
||||
disabled={isSaving}
|
||||
leftIcon={connectIcon}
|
||||
testID="direct-host-submit"
|
||||
>
|
||||
{isSaving ? t("pairing.direct.actions.connecting") : t("pairing.direct.actions.connect")}
|
||||
</Button>
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -587,14 +658,6 @@ const ThemedLink2 = withUnistyles(Link2, (theme) => ({ color: theme.colors.accen
|
||||
|
||||
const ThemedCheck = withUnistyles(Check, (theme) => ({ color: theme.colors.accentForeground }));
|
||||
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
editHost,
|
||||
editPromptPassword,
|
||||
editUri,
|
||||
openDirectConnection,
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
} from "./direct-connection";
|
||||
|
||||
const LABELS = { hostRequired: "Host is required", invalidPort: "Port is invalid" };
|
||||
const RELAY_LINK = "relay://relay.paseo.test:443/srv_abc?key=daemon-key&ssl=true";
|
||||
// The link `paseo daemon pair` prints first, next to the relay:// URI.
|
||||
const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
|
||||
JSON.stringify({
|
||||
v: 2,
|
||||
serverId: "srv_offer",
|
||||
daemonPublicKeyB64: "daemon-key",
|
||||
relay: { endpoint: "relay.paseo.test:443" },
|
||||
}),
|
||||
).toString("base64url")}`;
|
||||
|
||||
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
|
||||
const { host = "", ...rest } = fields;
|
||||
return editForm(editHost(openDirectConnection(), host), rest);
|
||||
}
|
||||
|
||||
function uri(text: string): DirectConnectionInput {
|
||||
return editUri(switchMode(openDirectConnection(), "uri"), text);
|
||||
}
|
||||
|
||||
describe("opening Direct connection", () => {
|
||||
it("opens as an empty form on the default port", () => {
|
||||
expect(openDirectConnection()).toEqual({
|
||||
mode: "form",
|
||||
host: "",
|
||||
port: "6767",
|
||||
useTls: false,
|
||||
password: "",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("switching from Form to URI", () => {
|
||||
it("leaves the URI empty when Host is empty", () => {
|
||||
expect(switchMode(openDirectConnection(), "uri")).toEqual({
|
||||
mode: "uri",
|
||||
uri: "",
|
||||
prompt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries host, port, SSL and password into the URI", () => {
|
||||
const input = form({ host: "192.168.1.20", port: "6767", useTls: true, password: "pw" });
|
||||
expect(switchMode(input, "uri")).toMatchObject({
|
||||
uri: "tcp://192.168.1.20:6767?ssl=true&password=pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes a pasted host:port or URL in Host", () => {
|
||||
expect(switchMode(form({ host: "myhost:7000" }), "uri")).toMatchObject({
|
||||
uri: "tcp://myhost:7000",
|
||||
});
|
||||
expect(switchMode(form({ host: "http://myhost:7000/" }), "uri")).toMatchObject({
|
||||
uri: "tcp://myhost:7000",
|
||||
});
|
||||
});
|
||||
|
||||
it("brackets an IPv6 host", () => {
|
||||
expect(switchMode(form({ host: "::1", port: "7000" }), "uri")).toMatchObject({
|
||||
uri: "tcp://[::1]:7000",
|
||||
});
|
||||
});
|
||||
|
||||
it("encodes a password with reserved characters", () => {
|
||||
const input = form({ host: "h", password: "a&b=c d" });
|
||||
const switched = switchMode(input, "uri");
|
||||
expect(switched).toMatchObject({ uri: "tcp://h:6767?password=a%26b%3Dc+d" });
|
||||
expect(switchMode(switched, "form")).toMatchObject({ password: "a&b=c d" });
|
||||
});
|
||||
|
||||
it("keeps an invalid port as text so Connect reports it", () => {
|
||||
expect(switchMode(form({ host: "host", port: "abc" }), "uri")).toMatchObject({
|
||||
uri: "tcp://host:abc",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("switching from URI to Form", () => {
|
||||
it("opens the default form when the URI is empty", () => {
|
||||
expect(switchMode(uri(""), "form")).toEqual(openDirectConnection());
|
||||
});
|
||||
|
||||
it("fills the fields from a valid URI", () => {
|
||||
expect(switchMode(uri("tcp://h:7443?ssl=true&password=x"), "form")).toEqual({
|
||||
mode: "form",
|
||||
host: "h",
|
||||
port: "7443",
|
||||
useTls: true,
|
||||
password: "x",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses a partial URI leniently", () => {
|
||||
expect(switchMode(uri("tcp://myhost"), "form")).toMatchObject({
|
||||
host: "myhost",
|
||||
port: "6767",
|
||||
});
|
||||
expect(switchMode(uri("myhost:70"), "form")).toMatchObject({ host: "myhost", port: "70" });
|
||||
expect(switchMode(uri("tcp://h:6767?pass"), "form")).toEqual({
|
||||
mode: "form",
|
||||
host: "h",
|
||||
port: "6767",
|
||||
useTls: false,
|
||||
password: "",
|
||||
});
|
||||
expect(switchMode(uri("tcp://host:abc"), "form")).toMatchObject({
|
||||
host: "host",
|
||||
port: "abc",
|
||||
});
|
||||
expect(switchMode(uri("tcp://[::1]:7000?ssl=true"), "form")).toMatchObject({
|
||||
host: "::1",
|
||||
port: "7000",
|
||||
useTls: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips any form with a host", () => {
|
||||
const forms = [
|
||||
form({ host: "example.paseo.test", port: "7443", useTls: true, password: "secret" }),
|
||||
form({ host: "::1", port: "7000" }),
|
||||
form({ host: "h", port: "abc" }),
|
||||
];
|
||||
for (const input of forms) {
|
||||
expect(switchMode(switchMode(input, "uri"), "form")).toEqual(input);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a pairing link in URI mode", () => {
|
||||
const relay = uri(RELAY_LINK);
|
||||
expect(canSwitchToForm(relay)).toBe(false);
|
||||
expect(switchMode(relay, "form")).toBe(relay);
|
||||
expect(canSwitchToForm(uri("https://app.paseo.sh/#connect=abc"))).toBe(false);
|
||||
expect(canSwitchToForm(uri(OFFER_LINK))).toBe(false);
|
||||
expect(canSwitchToForm(uri("tcp://h:1"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
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("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,
|
||||
});
|
||||
expect(editHost(openDirectConnection(), RELAY_LINK)).toMatchObject({
|
||||
mode: "uri",
|
||||
uri: RELAY_LINK,
|
||||
});
|
||||
expect(editHost(openDirectConnection(), "https://app.paseo.sh/#connect=abc")).toMatchObject({
|
||||
mode: "uri",
|
||||
});
|
||||
expect(editHost(openDirectConnection(), OFFER_LINK)).toEqual({
|
||||
mode: "uri",
|
||||
uri: OFFER_LINK,
|
||||
prompt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("password prompt", () => {
|
||||
it("asks for the host's password and keeps it while the target stays the same", () => {
|
||||
const prompted = editPromptPassword(promptForPassword(uri("tcp://h:7000")), "pw");
|
||||
expect(prompted).toMatchObject({ prompt: { host: "h:7000", password: "pw" } });
|
||||
expect(editUri(prompted, "tcp://h:7000?ssl=true")).toMatchObject({
|
||||
prompt: { host: "h:7000", password: "pw" },
|
||||
});
|
||||
expect(editUri(prompted, "tcp://h:70")).toMatchObject({ prompt: null });
|
||||
});
|
||||
|
||||
it("keeps the prompt while the URI is incomplete", () => {
|
||||
const prompted = promptForPassword(uri("tcp://h:7000"));
|
||||
expect(editUri(prompted, "tcp://")).toMatchObject({ prompt: { host: "h:7000" } });
|
||||
});
|
||||
|
||||
it("names a relay host by its server id", () => {
|
||||
expect(promptForPassword(uri(RELAY_LINK))).toMatchObject({ prompt: { host: "srv_abc" } });
|
||||
expect(promptForPassword(uri(OFFER_LINK))).toMatchObject({ prompt: { host: "srv_offer" } });
|
||||
});
|
||||
|
||||
it("keeps a typed password when the host asks again", () => {
|
||||
const prompted = editPromptPassword(promptForPassword(uri("tcp://h:7000")), "wrong");
|
||||
expect(promptForPassword(prompted)).toBe(prompted);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolving the connection", () => {
|
||||
it("connects to the form fields in Form mode", () => {
|
||||
expect(
|
||||
resolveConnection(form({ host: "h", port: "7000", useTls: true, password: "pw" }), LABELS),
|
||||
).toEqual({
|
||||
kind: "direct",
|
||||
uri: "tcp://h:7000?ssl=true",
|
||||
endpoint: "h:7000",
|
||||
useTls: true,
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports form validation errors", () => {
|
||||
expect(() => resolveConnection(openDirectConnection(), LABELS)).toThrow("Host is required");
|
||||
expect(() => resolveConnection(form({ host: "h", port: "abc" }), LABELS)).toThrow(
|
||||
"Port is invalid",
|
||||
);
|
||||
});
|
||||
|
||||
it("connects to the URI in URI mode", () => {
|
||||
expect(resolveConnection(uri("tcp://127.0.0.1:7000?password=pw"), LABELS)).toEqual({
|
||||
kind: "direct",
|
||||
uri: "tcp://127.0.0.1:7000",
|
||||
endpoint: "127.0.0.1:7000",
|
||||
useTls: false,
|
||||
password: "pw",
|
||||
});
|
||||
expect(resolveConnection(uri("tcp://[::1]:7000"), LABELS)).toMatchObject({
|
||||
endpoint: "[::1]:7000",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the prompt password over the URI password", () => {
|
||||
const input = editPromptPassword(promptForPassword(uri("tcp://h:7000?password=old")), "new");
|
||||
expect(resolveConnection(input, LABELS)).toMatchObject({ password: "new" });
|
||||
});
|
||||
|
||||
it("reports an invalid URI", () => {
|
||||
expect(() => resolveConnection(uri("tcp://host:abc"), LABELS)).toThrow();
|
||||
expect(() => resolveConnection(uri("tls://h:7000"), LABELS)).toThrow(
|
||||
"Connection URI protocol must be tcp:",
|
||||
);
|
||||
expect(() => resolveConnection(uri(""), LABELS)).toThrow("Connection URI is required");
|
||||
});
|
||||
|
||||
it("pairs through an offer link", () => {
|
||||
expect(resolveConnection(uri(OFFER_LINK), LABELS)).toEqual({ kind: "relay", link: OFFER_LINK });
|
||||
});
|
||||
|
||||
it("pairs through a relay link with the prompt password", () => {
|
||||
expect(resolveConnection(uri(` ${RELAY_LINK} `), LABELS)).toEqual({
|
||||
kind: "relay",
|
||||
link: RELAY_LINK,
|
||||
});
|
||||
const prompted = editPromptPassword(promptForPassword(uri(RELAY_LINK)), "pw");
|
||||
expect(resolveConnection(prompted, LABELS)).toEqual({
|
||||
kind: "relay",
|
||||
link: RELAY_LINK,
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
buildDirectConnectionUri,
|
||||
normalizeDirectConnectionHost,
|
||||
type DirectConnectionHostLabels,
|
||||
} from "@/components/direct-connection-host";
|
||||
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
|
||||
import {
|
||||
parseConnectionUri,
|
||||
parseRelayConnectionUri,
|
||||
serializeConnectionUri,
|
||||
} from "@/utils/daemon-endpoints";
|
||||
|
||||
/**
|
||||
* What the Direct connection step holds. The mode is the input: a hidden mode keeps no values,
|
||||
* so Connect can only read what the user sees.
|
||||
*/
|
||||
export type DirectConnectionInput = DirectConnectionForm | DirectConnectionUri;
|
||||
|
||||
export type DirectConnectionMode = DirectConnectionInput["mode"];
|
||||
|
||||
export interface DirectConnectionForm {
|
||||
mode: "form";
|
||||
host: string;
|
||||
port: string;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface DirectConnectionUri {
|
||||
mode: "uri";
|
||||
uri: string;
|
||||
/** The password a host asked for after Connect. Null until a host rejects the connection. */
|
||||
prompt: { host: string; password: string } | null;
|
||||
}
|
||||
|
||||
export type ResolvedDirectConnection =
|
||||
| { kind: "direct"; uri: string; endpoint: string; useTls: boolean; password?: string }
|
||||
| { 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: "" };
|
||||
}
|
||||
|
||||
/** Converts the input to the other mode. A pairing link stays a URI; see `canSwitchToForm`. */
|
||||
export function switchMode(
|
||||
input: DirectConnectionInput,
|
||||
mode: DirectConnectionMode,
|
||||
): DirectConnectionInput {
|
||||
if (input.mode === mode) return input;
|
||||
if (input.mode === "form") return { mode: "uri", uri: formToUri(input), prompt: null };
|
||||
if (!canSwitchToForm(input)) return input;
|
||||
return uriToForm(input.uri);
|
||||
}
|
||||
|
||||
export function canSwitchToForm(input: DirectConnectionInput): boolean {
|
||||
return input.mode === "form" || !isPairingLink(input.uri);
|
||||
}
|
||||
|
||||
export function editForm(
|
||||
input: DirectConnectionInput,
|
||||
fields: Partial<Omit<DirectConnectionForm, "mode" | "host">>,
|
||||
): DirectConnectionInput {
|
||||
if (input.mode !== "form") return input;
|
||||
return { ...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 {
|
||||
if (input.mode !== "form") return input;
|
||||
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
|
||||
return { ...input, host: 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;
|
||||
const target = uriHostLabel(text);
|
||||
const prompt = input.prompt && target && target !== input.prompt.host ? null : input.prompt;
|
||||
return { mode: "uri", uri: text, prompt };
|
||||
}
|
||||
|
||||
export function promptForPassword(input: DirectConnectionInput): DirectConnectionInput {
|
||||
if (input.mode !== "uri" || input.prompt) return input;
|
||||
return { ...input, prompt: { host: uriHostLabel(input.uri) ?? "host", password: "" } };
|
||||
}
|
||||
|
||||
export function editPromptPassword(
|
||||
input: DirectConnectionInput,
|
||||
password: string,
|
||||
): DirectConnectionInput {
|
||||
if (input.mode !== "uri" || !input.prompt) return input;
|
||||
return { ...input, prompt: { ...input.prompt, password } };
|
||||
}
|
||||
|
||||
/** What Connect dials. Throws the validation error to show when the input cannot connect. */
|
||||
export function resolveConnection(
|
||||
input: DirectConnectionInput,
|
||||
labels: DirectConnectionHostLabels,
|
||||
): ResolvedDirectConnection {
|
||||
if (input.mode === "form") {
|
||||
return resolveTcpUri(buildDirectConnectionUri(input, labels));
|
||||
}
|
||||
const uri = input.uri.trim();
|
||||
const promptPassword = input.prompt?.password || undefined;
|
||||
if (isPairingLink(uri)) {
|
||||
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
|
||||
}
|
||||
return resolveTcpUri(uri, promptPassword);
|
||||
}
|
||||
|
||||
function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectConnection {
|
||||
const parsed = parseConnectionUri(uri);
|
||||
const password = passwordOverride ?? parsed.password;
|
||||
return {
|
||||
kind: "direct",
|
||||
uri: serializeConnectionUri(parsed),
|
||||
endpoint: parsed.isIpv6 ? `[${parsed.host}]:${parsed.port}` : `${parsed.host}:${parsed.port}`,
|
||||
useTls: parsed.useTls,
|
||||
...(password ? { password } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
|
||||
function isPairingLink(uri: string): boolean {
|
||||
const trimmed = uri.trim();
|
||||
return (
|
||||
trimmed.toLowerCase().startsWith("relay://") ||
|
||||
trimmed.includes("#connect=") ||
|
||||
trimmed.includes("#offer=")
|
||||
);
|
||||
}
|
||||
|
||||
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 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 (input.useTls) query.set("ssl", "true");
|
||||
if (input.password) query.set("password", input.password);
|
||||
const search = query.toString();
|
||||
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
|
||||
}
|
||||
|
||||
function uriToForm(uri: string): DirectConnectionForm {
|
||||
const address = splitUri(uri);
|
||||
if (!address.host) return openDirectConnection();
|
||||
return {
|
||||
mode: "form",
|
||||
host: address.host,
|
||||
port: address.port ?? DEFAULT_PORT,
|
||||
useTls: address.query.get("ssl") === "true",
|
||||
password: address.query.get("password") ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function uriHostLabel(uri: string): string | null {
|
||||
const trimmed = uri.trim();
|
||||
if (isPairingLink(trimmed)) {
|
||||
try {
|
||||
return trimmed.includes("#offer=")
|
||||
? (parseConnectionOfferFromUrl(trimmed)?.serverId ?? null)
|
||||
: parseRelayConnectionUri(trimmed).offer.serverId;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
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 };
|
||||
}
|
||||
@@ -1997,7 +1997,6 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "اتصال مباشر",
|
||||
helper: "أدخل عنوان خادم Paseo.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "ميناء",
|
||||
@@ -2006,10 +2005,10 @@ export const ar: TranslationResources = {
|
||||
useSsl: "استخدم طبقة المقابس الآمنة",
|
||||
connectionUri: "معرف URI للاتصال",
|
||||
},
|
||||
advanced: {
|
||||
label: "متقدم",
|
||||
show: "عرض متقدم",
|
||||
hide: "إخفاء المتقدمة",
|
||||
modes: {
|
||||
form: "نموذج",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "روابط الاقتران تعمل كـ URI فقط",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "إظهار كلمة المرور",
|
||||
|
||||
@@ -2027,7 +2027,6 @@ export const en = {
|
||||
},
|
||||
direct: {
|
||||
title: "Direct connection",
|
||||
helper: "Enter the address of a Paseo server.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "Port",
|
||||
@@ -2036,10 +2035,10 @@ export const en = {
|
||||
useSsl: "Use SSL",
|
||||
connectionUri: "Connection URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "Advanced",
|
||||
show: "Show advanced",
|
||||
hide: "Hide advanced",
|
||||
modes: {
|
||||
form: "Form",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Pairing links only work as a URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Show password",
|
||||
|
||||
@@ -2051,7 +2051,6 @@ export const es: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Conexión directa",
|
||||
helper: "Ingrese la dirección de un servidorPaseo.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "Puerto",
|
||||
@@ -2060,10 +2059,10 @@ export const es: TranslationResources = {
|
||||
useSsl: "Usar SSL",
|
||||
connectionUri: "URI de conexión",
|
||||
},
|
||||
advanced: {
|
||||
label: "Avanzado",
|
||||
show: "Mostrar avanzado",
|
||||
hide: "Ocultar avanzado",
|
||||
modes: {
|
||||
form: "Formulario",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Los enlaces de emparejamiento solo funcionan como URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Mostrar contraseña",
|
||||
|
||||
@@ -2048,7 +2048,6 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Connexion directe",
|
||||
helper: "Saisissez l’adresse d’un serveur Paseo.",
|
||||
fields: {
|
||||
host: "Hôte",
|
||||
port: "Port",
|
||||
@@ -2057,10 +2056,10 @@ export const fr: TranslationResources = {
|
||||
useSsl: "Utiliser SSL",
|
||||
connectionUri: "URI de connexion",
|
||||
},
|
||||
advanced: {
|
||||
label: "Options avancées",
|
||||
show: "Afficher les options avancées",
|
||||
hide: "Masquer les options avancées",
|
||||
modes: {
|
||||
form: "Formulaire",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Les liens d’association ne fonctionnent qu’en URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Afficher le mot de passe",
|
||||
|
||||
@@ -2018,7 +2018,6 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "直接接続",
|
||||
helper: "Paseoサーバーのアドレスを入力してください。",
|
||||
fields: {
|
||||
host: "ホスト",
|
||||
port: "ポート",
|
||||
@@ -2027,10 +2026,10 @@ export const ja: TranslationResources = {
|
||||
useSsl: "SSLを使用",
|
||||
connectionUri: "接続URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "詳細設定",
|
||||
show: "詳細設定を表示",
|
||||
hide: "詳細設定を非表示",
|
||||
modes: {
|
||||
form: "フォーム",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "ペアリングリンクはURIでのみ使用できます",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "パスワードを表示",
|
||||
|
||||
@@ -2009,7 +2009,6 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "직접 연결",
|
||||
helper: "Paseo 서버의 주소를 입력하세요.",
|
||||
fields: {
|
||||
host: "호스트",
|
||||
port: "포트",
|
||||
@@ -2018,10 +2017,10 @@ export const ko: TranslationResources = {
|
||||
useSsl: "SSL 사용",
|
||||
connectionUri: "연결 URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "고급",
|
||||
show: "고급 표시",
|
||||
hide: "고급 숨기기",
|
||||
modes: {
|
||||
form: "양식",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "페어링 링크는 URI로만 사용할 수 있습니다",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "비밀번호 표시",
|
||||
|
||||
@@ -2035,7 +2035,6 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Conexão direta",
|
||||
helper: "Informe o endereço de um servidor Paseo.",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "Porta",
|
||||
@@ -2044,10 +2043,10 @@ export const ptBR: TranslationResources = {
|
||||
useSsl: "Usar SSL",
|
||||
connectionUri: "URI da conexão",
|
||||
},
|
||||
advanced: {
|
||||
label: "Avançado",
|
||||
show: "Mostrar avançado",
|
||||
hide: "Ocultar avançado",
|
||||
modes: {
|
||||
form: "Formulário",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Links de pareamento só funcionam como URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Mostrar senha",
|
||||
|
||||
@@ -2034,7 +2034,6 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "Прямое подключение",
|
||||
helper: "Введите адрес сервера Paseo.",
|
||||
fields: {
|
||||
host: "Хост",
|
||||
port: "Порт",
|
||||
@@ -2043,10 +2042,10 @@ export const ru: TranslationResources = {
|
||||
useSsl: "Использовать SSL",
|
||||
connectionUri: "URI подключения",
|
||||
},
|
||||
advanced: {
|
||||
label: "Дополнительные параметры",
|
||||
show: "Показать дополнительные параметры",
|
||||
hide: "Скрыть дополнительные параметры",
|
||||
modes: {
|
||||
form: "Форма",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "Ссылки для сопряжения работают только как URI",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "Показать пароль",
|
||||
|
||||
@@ -1978,7 +1978,6 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
direct: {
|
||||
title: "直接连接",
|
||||
helper: "输入 Paseo server 的地址。",
|
||||
fields: {
|
||||
host: "Host",
|
||||
port: "端口",
|
||||
@@ -1987,10 +1986,10 @@ export const zhCN: TranslationResources = {
|
||||
useSsl: "使用 SSL",
|
||||
connectionUri: "连接 URI",
|
||||
},
|
||||
advanced: {
|
||||
label: "高级",
|
||||
show: "显示高级选项",
|
||||
hide: "隐藏高级选项",
|
||||
modes: {
|
||||
form: "表单",
|
||||
uri: "URI",
|
||||
uriOnlyLink: "配对链接只能以 URI 形式使用",
|
||||
},
|
||||
passwordVisibility: {
|
||||
show: "显示密码",
|
||||
|
||||
Reference in New Issue
Block a user